Example #1
0
        private void GenerateMaterials()
        {
            var matFolders = importers.Where(im => im.materialLocation == SpeedTreeImporter.MaterialLocation.External).Select(im => im.materialFolderPath).ToList();
            var guids      = AssetDatabase.FindAssets("t:Material", matFolders.ToArray());
            var paths      = guids.Select(guid => AssetDatabase.GUIDToAssetPath(guid)).ToList();

            var importersWithEmbeddedMaterials = importers.Where(im => im.materialLocation == SpeedTreeImporter.MaterialLocation.InPrefab);

            foreach (var importer in importersWithEmbeddedMaterials)
            {
                var remappedAssets = importer.GetExternalObjectMap();
                var materials      = remappedAssets.Where(kv => kv.Value is Material && kv.Value != null).Select(kv => kv.Value);
                foreach (var material in materials)
                {
                    var path = AssetDatabase.GetAssetPath(material);
                    paths.Add(path);
                    matFolders.Add(FileUtil.DeleteLastPathNameComponent(path));
                }
            }

            bool doGenerate = true;

            if (paths.Count() > 0)
            {
                doGenerate = Provider.PromptAndCheckoutIfNeeded(paths.ToArray(), String.Format("Materials will be checked out in:\n{0}", String.Join("\n", matFolders.ToArray())));
            }

            if (doGenerate)
            {
                foreach (var importer in importers)
                {
                    importer.GenerateMaterials();
                }
            }
        }
Example #2
0
        private bool ExtractMaterialsGUI()
        {
            using (new EditorGUILayout.HorizontalScope())
            {
                EditorGUILayout.PrefixLabel(Styles.Materials);
                using (new EditorGUI.DisabledScope(!CanExtractEmbeddedMaterials()))
                {
                    if (GUILayout.Button(Styles.ExtractEmbeddedMaterials))
                    {
                        // use the first target for selecting the destination folder, but apply that path for all targets
                        string destinationPath = (target as ModelImporter).assetPath;
                        destinationPath = EditorUtility.SaveFolderPanel("Select Materials Folder",
                                                                        FileUtil.DeleteLastPathNameComponent(destinationPath), "");
                        if (string.IsNullOrEmpty(destinationPath))
                        {
                            // cancel the extraction if the user did not select a folder
                            return(false);
                        }

                        destinationPath = FileUtil.GetProjectRelativePath(destinationPath);

                        //Where all the required embedded materials are not in the asset database, we need to reimport them
                        if (!AllEmbeddedMaterialsAreImported())
                        {
                            if (EditorUtility.DisplayDialog(L10n.Tr("Are you sure you want to re-extract the Materials?"), L10n.Tr("In order to re-extract the Materials we'll need to reimport the mesh, this might take a while. Do you want to continue?"), L10n.Tr("Yes"), L10n.Tr("No")))
                            {
                                ReimportEmbeddedMaterials();
                            }
                            else
                            {
                                return(false);
                            }
                        }

                        try
                        {
                            // batch the extraction of the textures
                            AssetDatabase.StartAssetEditing();
                            PrefabUtility.ExtractMaterialsFromAsset(targets, destinationPath);
                        }
                        finally
                        {
                            AssetDatabase.StopAssetEditing();
                        }

                        // AssetDatabase.StopAssetEditing() invokes OnEnable(), which invalidates all the serialized properties, so we must return.
                        return(true);
                    }
                }
            }

            return(false);
        }
 private void AddAssetItem(string guid, string pathName, bool isDir, ChangeFlags changeFlags, int changeset)
 {
     if (pathName == string.Empty)
     {
         return;
     }
     if (isDir)
     {
         string str   = ParentViewFolder.MakeNiceName(pathName);
         int    index = ParentViewState.IndexOf(this.folders, str);
         if (index == -1)
         {
             ArrayUtility.Add <ParentViewFolder>(ref this.folders, new ParentViewFolder(str, guid, changeFlags));
         }
         else
         {
             this.folders[index].changeFlags = changeFlags;
             this.folders[index].guid        = guid;
         }
     }
     else
     {
         string           str1   = ParentViewFolder.MakeNiceName(FileUtil.DeleteLastPathNameComponent(pathName));
         string           str2   = pathName.Substring(pathName.LastIndexOf("/") + 1);
         int              index1 = ParentViewState.IndexOf(this.folders, str1);
         ParentViewFolder parentViewFolder;
         if (index1 == -1)
         {
             parentViewFolder = new ParentViewFolder(str1, AssetServer.GetParentGUID(guid, changeset));
             ArrayUtility.Add <ParentViewFolder>(ref this.folders, parentViewFolder);
         }
         else
         {
             parentViewFolder = this.folders[index1];
         }
         int index2 = ParentViewState.IndexOf(parentViewFolder.files, str2);
         if (index2 != -1)
         {
             if ((parentViewFolder.files[index2].changeFlags & ChangeFlags.Deleted) != ChangeFlags.None)
             {
                 return;
             }
             parentViewFolder.files[index2].guid        = guid;
             parentViewFolder.files[index2].changeFlags = changeFlags;
         }
         else
         {
             ArrayUtility.Add <ParentViewFile>(ref parentViewFolder.files, new ParentViewFile(str2, guid, changeFlags));
         }
     }
 }
Example #4
0
		private void AddAssetItem(string guid, string pathName, bool isDir, ChangeFlags changeFlags, int changeset)
		{
			if (!(pathName == string.Empty))
			{
				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<ParentViewFolder>(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<ParentViewFolder>(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;
						}
					}
					else
					{
						ArrayUtility.Add<ParentViewFile>(ref parentViewFolder.files, new ParentViewFile(text3, guid, changeFlags));
					}
				}
			}
		}
 private void AddAssetItem(string guid, string pathName, bool isDir, ChangeFlags changeFlags, int changeset)
 {
     if (pathName != string.Empty)
     {
         if (isDir)
         {
             string lfname = ParentViewFolder.MakeNiceName(pathName);
             int    index  = IndexOf(this.folders, lfname);
             if (index == -1)
             {
                 ParentViewFolder item = new ParentViewFolder(lfname, guid, changeFlags);
                 ArrayUtility.Add <ParentViewFolder>(ref this.folders, item);
             }
             else
             {
                 this.folders[index].changeFlags = changeFlags;
                 this.folders[index].guid        = guid;
             }
         }
         else
         {
             ParentViewFolder folder2;
             string           str2 = ParentViewFolder.MakeNiceName(FileUtil.DeleteLastPathNameComponent(pathName));
             string           str3 = pathName.Substring(pathName.LastIndexOf("/") + 1);
             int num2 = IndexOf(this.folders, str2);
             if (num2 == -1)
             {
                 folder2 = new ParentViewFolder(str2, AssetServer.GetParentGUID(guid, changeset));
                 ArrayUtility.Add <ParentViewFolder>(ref this.folders, folder2);
             }
             else
             {
                 folder2 = this.folders[num2];
             }
             num2 = IndexOf(folder2.files, str3);
             if (num2 != -1)
             {
                 if ((folder2.files[num2].changeFlags & ChangeFlags.Deleted) == ChangeFlags.None)
                 {
                     folder2.files[num2].guid        = guid;
                     folder2.files[num2].changeFlags = changeFlags;
                 }
             }
             else
             {
                 ArrayUtility.Add <ParentViewFile>(ref folder2.files, new ParentViewFile(str3, guid, changeFlags));
             }
         }
     }
 }
Example #6
0
        private bool ExtractMaterialsGUI()
        {
            using (new EditorGUILayout.HorizontalScope())
            {
                EditorGUILayout.PrefixLabel(Styles.Materials);
                using (new EditorGUI.DisabledScope(!HasEmbeddedMaterials()))
                {
                    if (GUILayout.Button(Styles.ExtractEmbeddedMaterials))
                    {
                        // use the first target for selecting the destination folder, but apply that path for all targets
                        string destinationPath = (target as ModelImporter).assetPath;
                        destinationPath = EditorUtility.SaveFolderPanel("Select Materials Folder",
                                                                        FileUtil.DeleteLastPathNameComponent(destinationPath), "");
                        if (string.IsNullOrEmpty(destinationPath))
                        {
                            // cancel the extraction if the user did not select a folder
                            return(false);
                        }
                        destinationPath = FileUtil.GetProjectRelativePath(destinationPath);

                        try
                        {
                            // batch the extraction of the textures
                            AssetDatabase.StartAssetEditing();

                            PrefabUtility.ExtractMaterialsFromAsset(targets, destinationPath);
                        }
                        finally
                        {
                            AssetDatabase.StopAssetEditing();
                        }

                        // AssetDatabase.StopAssetEditing() invokes OnEnable(), which invalidates all the serialized properties, so we must return.
                        return(true);
                    }
                }
            }

            return(false);
        }
Example #7
0
        internal static void ExtractSelectedObjectsFromPrefab()
        {
            HashSet <string> hashSet = new HashSet <string>();
            string           text    = null;

            UnityEngine.Object[] objects = Selection.objects;
            for (int i = 0; i < objects.Length; i++)
            {
                UnityEngine.Object @object   = objects[i];
                string             assetPath = AssetDatabase.GetAssetPath(@object);
                if (text == null)
                {
                    text = EditorUtility.SaveFolderPanel("Select Materials Folder", FileUtil.DeleteLastPathNameComponent(assetPath), "");
                    if (string.IsNullOrEmpty(text))
                    {
                        return;
                    }
                    text = FileUtil.GetProjectRelativePath(text);
                }
                string str   = (!(@object is Material)) ? string.Empty : ".mat";
                string text2 = FileUtil.CombinePaths(new string[]
                {
                    text,
                    @object.name
                }) + str;
                text2 = AssetDatabase.GenerateUniqueAssetPath(text2);
                string value = AssetDatabase.ExtractAsset(@object, text2);
                if (string.IsNullOrEmpty(value))
                {
                    hashSet.Add(assetPath);
                }
            }
            foreach (string current in hashSet)
            {
                AssetDatabase.WriteImportSettingsIfDirty(current);
                AssetDatabase.ImportAsset(current, ImportAssetOptions.ForceUpdate);
            }
        }
            private static bool PickBuildLocation(BuildTargetGroup targetGroup, BuildTarget target, BuildOptions options, out bool updateExistingBuild)
            {
                updateExistingBuild = false;
                var previousPath = EditorUserBuildSettings.GetBuildLocation(target);

                string defaultFolder;
                string defaultName;

                if (previousPath == String.Empty)
                {
                    defaultFolder = FileUtil.DeleteLastPathNameComponent(Application.dataPath);
                    defaultName   = "";
                }
                else
                {
                    defaultFolder = FileUtil.DeleteLastPathNameComponent(previousPath);
                    defaultName   = FileUtil.GetLastPathNameComponent(previousPath);
                }

                string extension = PostprocessBuildPlayer.GetExtensionForBuildTarget(targetGroup, target, options);

                // Invalidate default name, if extension mismatches the default file (for ex., when switching between folder type export to file type export, see Android)
                if (extension != Path.GetExtension(defaultName).Replace(".", ""))
                {
                    defaultName = string.Empty;
                }

                // Hack: For Windows Standalone, we want the BuildPanel to choose a folder,
                // but we don't want BuildPlayer to take a folder path because historically it took an .exe path
                // and we would be breaking tons of projects!
                bool   isWindowsStandalone = target == BuildTarget.StandaloneWindows || target == BuildTarget.StandaloneWindows64;
                string realExtension       = extension;

                if (isWindowsStandalone)
                {
                    extension = string.Empty;
                    // Remove the filename.exe part from the path
                    if (!string.IsNullOrEmpty(defaultName))
                    {
                        defaultName = Path.GetDirectoryName(defaultName);
                    }
                }

                string title = "Build " + BuildPlatforms.instance.GetBuildTargetDisplayName(targetGroup, target);
                string path  = EditorUtility.SaveBuildPanel(target, title, defaultFolder, defaultName, extension, out updateExistingBuild);

                if (path == string.Empty)
                {
                    return(false);
                }

                if (isWindowsStandalone)
                {
                    extension = realExtension;
                    path      = Path.Combine(path, Paths.MakeValidFileName(PlayerSettings.productName) + '.' + extension);
                }

                if (!IsBuildPathValid(path))
                {
                    return(false);
                }

                // Enforce extension if needed
                if (extension != string.Empty && FileUtil.GetPathExtension(path).ToLower() != extension)
                {
                    path += '.' + extension;
                }

                // A path may not be empty initially, but it could contain, e.g., a drive letter (as in Windows),
                // so even appending an extension will work fine, but in reality the name will be, for example,
                // G:/
                //Debug.Log(path);

                string currentlyChosenName = FileUtil.GetLastPathNameComponent(path);

                if (currentlyChosenName == string.Empty)
                {
                    return(false); // No nameless projects, please
                }
                // We don't want to re-create a directory that already exists, this may
                // result in access-denials that will make users unhappy.
                string check_dir = extension != string.Empty ? FileUtil.DeleteLastPathNameComponent(path) : path;

                if (!Directory.Exists(check_dir))
                {
                    Directory.CreateDirectory(check_dir);
                }

                // On OSX we've got replace/update dialog, for other platforms warn about deleting
                // files in target folder.
                if ((target == BuildTarget.iOS) && (Application.platform != RuntimePlatform.OSXEditor))
                {
                    if (!FolderIsEmpty(path) && !UserWantsToDeleteFiles(path))
                    {
                        return(false);
                    }
                }

                EditorUserBuildSettings.SetBuildLocation(target, path);
                return(true);
            }
 static bool BuildLocationIsValid(string path)
 {
     return(path.Length > 0 && System.IO.Directory.Exists(FileUtil.DeleteLastPathNameComponent(path)));
 }
Example #10
0
        private void ExtractTexturesGUI()
        {
            using (new EditorGUILayout.HorizontalScope())
            {
                EditorGUILayout.PrefixLabel(Styles.Textures);

                using (
                    new EditorGUI.DisabledScope(!m_HasEmbeddedTextures.boolValue &&
                                                !m_HasEmbeddedTextures.hasMultipleDifferentValues))
                {
                    if (GUILayout.Button(Styles.ExtractEmbeddedTextures))
                    {
                        // when extracting textures, we must handle the case when multiple selected assets could generate textures with the same name at the user supplied path
                        // we proceed as follows:
                        // 1. each asset extracts the textures in a separate temp folder
                        // 2. we remap the extracted assets to the respective asset importer
                        // 3. we generate unique names for each asset and move them to the user supplied path
                        // 4. we re-import all the assets to have the internal materials linked to the newly extracted textures

                        List <Tuple <Object, string> > outputsForTargets = new List <Tuple <Object, string> >();
                        // use the first target for selecting the destination folder, but apply that path for all targets
                        string destinationPath = (target as ModelImporter).assetPath;
                        destinationPath = EditorUtility.SaveFolderPanel("Select Textures Folder",
                                                                        FileUtil.DeleteLastPathNameComponent(destinationPath), "");
                        if (string.IsNullOrEmpty(destinationPath))
                        {
                            // cancel the extraction if the user did not select a folder
                            return;
                        }
                        destinationPath = FileUtil.GetProjectRelativePath(destinationPath);

                        try
                        {
                            // batch the extraction of the textures
                            AssetDatabase.StartAssetEditing();

                            foreach (var t in targets)
                            {
                                var tempPath = FileUtil.GetUniqueTempPathInProject();
                                tempPath = tempPath.Replace("Temp", UnityEditorInternal.InternalEditorUtility.GetAssetsFolder());
                                outputsForTargets.Add(Tuple.Create(t, tempPath));

                                var importer = t as ModelImporter;
                                importer.ExtractTextures(tempPath);
                            }
                        }
                        finally
                        {
                            AssetDatabase.StopAssetEditing();
                        }

                        try
                        {
                            // batch the remapping and the reimport of the assets
                            AssetDatabase.Refresh();
                            AssetDatabase.StartAssetEditing();

                            foreach (var item in outputsForTargets)
                            {
                                var importer = item.Item1 as ModelImporter;

                                var guids = AssetDatabase.FindAssets("t:Texture", new string[] { item.Item2 });

                                foreach (var guid in guids)
                                {
                                    var path = AssetDatabase.GUIDToAssetPath(guid);
                                    var tex  = AssetDatabase.LoadAssetAtPath <Texture>(path);
                                    if (tex == null)
                                    {
                                        continue;
                                    }

                                    importer.AddRemap(new AssetImporter.SourceAssetIdentifier(tex), tex);

                                    var newPath = Path.Combine(destinationPath, FileUtil.UnityGetFileName(path));
                                    newPath = AssetDatabase.GenerateUniqueAssetPath(newPath);
                                    AssetDatabase.MoveAsset(path, newPath);
                                }

                                AssetDatabase.ImportAsset(importer.assetPath, ImportAssetOptions.ForceUpdate);

                                AssetDatabase.DeleteAsset(item.Item2);
                            }
                        }
                        finally
                        {
                            AssetDatabase.StopAssetEditing();
                        }
                    }
                }
            }
        }
Example #11
0
        internal static void ExtractSelectedObjectsFromPrefab()
        {
            var    assetsToReload = new HashSet <string>();
            string folder         = null;

            foreach (var selectedObj in Selection.objects)
            {
                var path = AssetDatabase.GetAssetPath(selectedObj);

                // use the first selected element as the basis for the folder path where all the materials will be extracted
                if (folder == null)
                {
                    folder = EditorUtility.SaveFolderPanel("Select Materials Folder", FileUtil.DeleteLastPathNameComponent(path), "");
                    if (string.IsNullOrEmpty(folder))
                    {
                        // cancel the extraction if the user did not select a folder
                        return;
                    }

                    folder = FileUtil.GetProjectRelativePath(folder);
                }

                // TODO: [bogdanc 3/6/2017] if we want this function really generic, we need to know what extension the new asset files should have
                var extension    = selectedObj is Material ? kMaterialExtension : string.Empty;
                var newAssetPath = FileUtil.CombinePaths(folder, selectedObj.name) + extension;
                newAssetPath = AssetDatabase.GenerateUniqueAssetPath(newAssetPath);

                var error = AssetDatabase.ExtractAsset(selectedObj, newAssetPath);
                if (string.IsNullOrEmpty(error))
                {
                    assetsToReload.Add(path);
                }
            }

            foreach (var path in assetsToReload)
            {
                AssetDatabase.WriteImportSettingsIfDirty(path);
                AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
            }
        }
Example #12
0
        private bool ExtractMaterialsGUI()
        {
            bool result;

            using (new EditorGUILayout.HorizontalScope(new GUILayoutOption[0]))
            {
                EditorGUILayout.PrefixLabel(ModelImporterMaterialEditor.Styles.Materials);
                using (new EditorGUI.DisabledScope(!this.HasEmbeddedMaterials()))
                {
                    if (GUILayout.Button(ModelImporterMaterialEditor.Styles.ExtractEmbeddedMaterials, new GUILayoutOption[0]))
                    {
                        string text = (base.target as ModelImporter).assetPath;
                        text = EditorUtility.SaveFolderPanel("Select Materials Folder", FileUtil.DeleteLastPathNameComponent(text), "");
                        if (string.IsNullOrEmpty(text))
                        {
                            result = false;
                            return(result);
                        }
                        text = FileUtil.GetProjectRelativePath(text);
                        try
                        {
                            AssetDatabase.StartAssetEditing();
                            PrefabUtility.ExtractMaterialsFromAsset(base.targets, text);
                        }
                        finally
                        {
                            AssetDatabase.StopAssetEditing();
                        }
                        result = true;
                        return(result);
                    }
                }
            }
            result = false;
            return(result);
        }
Example #13
0
 private void ExtractTexturesGUI()
 {
     using (new EditorGUILayout.HorizontalScope(new GUILayoutOption[0]))
     {
         EditorGUILayout.PrefixLabel(ModelImporterMaterialEditor.Styles.Textures);
         using (new EditorGUI.DisabledScope(!this.m_HasEmbeddedTextures.boolValue && !this.m_HasEmbeddedTextures.hasMultipleDifferentValues))
         {
             if (GUILayout.Button(ModelImporterMaterialEditor.Styles.ExtractEmbeddedTextures, new GUILayoutOption[0]))
             {
                 List <Tuple <UnityEngine.Object, string> > list = new List <Tuple <UnityEngine.Object, string> >();
                 string text = (base.target as ModelImporter).assetPath;
                 text = EditorUtility.SaveFolderPanel("Select Textures Folder", FileUtil.DeleteLastPathNameComponent(text), "");
                 if (!string.IsNullOrEmpty(text))
                 {
                     text = FileUtil.GetProjectRelativePath(text);
                     try
                     {
                         AssetDatabase.StartAssetEditing();
                         UnityEngine.Object[] targets = base.targets;
                         for (int i = 0; i < targets.Length; i++)
                         {
                             UnityEngine.Object @object = targets[i];
                             string             text2   = FileUtil.GetUniqueTempPathInProject();
                             text2 = text2.Replace("Temp", InternalEditorUtility.GetAssetsFolder());
                             list.Add(Tuple.Create <UnityEngine.Object, string>(@object, text2));
                             ModelImporter modelImporter = @object as ModelImporter;
                             modelImporter.ExtractTextures(text2);
                         }
                     }
                     finally
                     {
                         AssetDatabase.StopAssetEditing();
                     }
                     try
                     {
                         AssetDatabase.Refresh();
                         AssetDatabase.StartAssetEditing();
                         foreach (Tuple <UnityEngine.Object, string> current in list)
                         {
                             ModelImporter modelImporter2 = current.Item1 as ModelImporter;
                             string[]      array          = AssetDatabase.FindAssets("t:Texture", new string[]
                             {
                                 current.Item2
                             });
                             string[] array2 = array;
                             for (int j = 0; j < array2.Length; j++)
                             {
                                 string  guid    = array2[j];
                                 string  text3   = AssetDatabase.GUIDToAssetPath(guid);
                                 Texture texture = AssetDatabase.LoadAssetAtPath <Texture>(text3);
                                 if (!(texture == null))
                                 {
                                     modelImporter2.AddRemap(new AssetImporter.SourceAssetIdentifier(texture), texture);
                                     string text4 = Path.Combine(text, FileUtil.UnityGetFileName(text3));
                                     text4 = AssetDatabase.GenerateUniqueAssetPath(text4);
                                     AssetDatabase.MoveAsset(text3, text4);
                                 }
                             }
                             AssetDatabase.ImportAsset(modelImporter2.assetPath, ImportAssetOptions.ForceUpdate);
                             AssetDatabase.DeleteAsset(current.Item2);
                         }
                     }
                     finally
                     {
                         AssetDatabase.StopAssetEditing();
                     }
                 }
             }
         }
     }
 }