示例#1
0
        public virtual bool AvoidOverwriteAndLoad(UnityPath assetPath, UnityEngine.Object o)
        {
            if (o is Material)
            {
                var loaded = assetPath.LoadAsset <Material>();

                // replace component reference
                foreach (var mesh in Meshes)
                {
                    foreach (var r in mesh.Renderers)
                    {
                        for (int i = 0; i < r.sharedMaterials.Length; ++i)
                        {
                            if (r.sharedMaterials.Contains(o))
                            {
                                r.sharedMaterials = r.sharedMaterials.Select(x => x == o ? loaded : x).ToArray();
                            }
                        }
                    }
                }

                return(true);
            }

            return(false);
        }
示例#2
0
        public void CreateTextureItems(UnityPath imageBaseDir = default(UnityPath))
        {
            if (m_textures.Any())
            {
                return;
            }

            for (int i = 0; i < GLTF.textures.Count; ++i)
            {
                TextureItem item = null;
#if UNITY_EDITOR
                var image = GLTF.GetImageFromTextureIndex(i);
                if (imageBaseDir.IsUnderAssetsFolder &&
                    !string.IsNullOrEmpty(image.uri) &&
                    !image.uri.StartsWith("data:")
                    )
                {
                    ///
                    /// required SaveTexturesAsPng or SetTextureBaseDir
                    ///
                    var assetPath   = imageBaseDir.Child(image.uri);
                    var textureName = !string.IsNullOrEmpty(image.name) ? image.name : Path.GetFileNameWithoutExtension(image.uri);
                    item = new TextureItem(i, assetPath, textureName);
                }
                else
#endif
                {
                    item = new TextureItem(i, CreateTextureLoader(i));
                }

                AddTexture(item);
            }
        }
示例#3
0
 protected virtual UnityPath GetAssetPath(UnityPath prefabPath, UnityEngine.Object o)
 {
     if (o is Material)
     {
         var materialDir  = prefabPath.GetAssetFolder(".Materials");
         var materialPath = materialDir.Child(o.name.EscapeFilePath() + ".asset");
         return(materialPath);
     }
     else if (o is Texture2D)
     {
         var textureDir  = prefabPath.GetAssetFolder(".Textures");
         var texturePath = textureDir.Child(o.name.EscapeFilePath() + ".asset");
         return(texturePath);
     }
     else if (o is Mesh && !MeshAsSubAsset)
     {
         var meshDir  = prefabPath.GetAssetFolder(".Meshes");
         var meshPath = meshDir.Child(o.name.EscapeFilePath() + ".asset");
         return(meshPath);
     }
     else
     {
         return(default(UnityPath));
     }
 }
示例#4
0
 static void ImportDelayed(string src, UnityPath prefabPath, ImporterContext context)
 {
     EditorApplication.delayCall += () =>
     {
         //
         // After textures imported(To ensure TextureImporter be accessible).
         //
         try
         {
             context.Load();
             context.SaveAsAsset(prefabPath);
             context.EditorDestroyRoot();
         }
         catch (UniGLTFNotSupportedException ex)
         {
             Debug.LogWarningFormat("{0}: {1}",
                                    src,
                                    ex.Message
                                    );
             context.EditorDestroyRootAndAssets();
         }
         catch (Exception ex)
         {
             Debug.LogErrorFormat("import error: {0}", src);
             Debug.LogErrorFormat("{0}", ex);
             context.EditorDestroyRootAndAssets();
         }
     };
 }
示例#5
0
        static void OnPostprocessAllAssets(string[] importedAssets,
                                           string[] deletedAssets,
                                           string[] movedAssets,
                                           string[] movedFromAssetPaths)
        {
            foreach (string path in importedAssets)
            {
                if (UnityPath.FromUnityPath(path).IsStreamingAsset)
                {
                    Debug.LogFormat("Skip StreamingAssets: {0}", path);
                    continue;
                }

                var ext = Path.GetExtension(path).ToLower();
                switch (ext)
                {
                case ".gltf":
                case ".glb":
                {
                    var gltfPath   = UnityPath.FromUnityPath(path);
                    var prefabPath = gltfPath.Parent.Child(gltfPath.FileNameWithoutExtension + ".prefab");
                    ImportAsset(UnityPath.FromUnityPath(path).FullPath, ext, prefabPath);
                    break;
                }
                }
            }
        }
        public static void IntegrateSelected()
        {
            var go = Selection.activeObject as GameObject;
            var meshWithMaterials = Integrate(go.transform);

            // save as asset
            var assetPath = "";

#if UNITY_2018_2_OR_NEWER
            var prefab = PrefabUtility.GetCorrespondingObjectFromSource(go);
#else
            var prefab = PrefabUtility.GetPrefabParent(go);
#endif
            if (prefab != null)
            {
                var prefabPath = AssetDatabase.GetAssetPath(prefab);
                assetPath = string.Format("{0}/{1}_{2}{3}",
                                          Path.GetDirectoryName(prefabPath),
                                          Path.GetFileNameWithoutExtension(prefabPath),
                                          go.name,
                                          ASSET_SUFFIX
                                          );
            }
            else
            {
                var path = EditorUtility.SaveFilePanel(
                    "Save mesh",
                    "Assets",
                    go.name + ".asset",
                    "asset");
                if (string.IsNullOrEmpty(path))
                {
                    return;
                }
                assetPath = UnityPath.FromFullpath(path).Value;
            }

            assetPath = AssetDatabase.GenerateUniqueAssetPath(assetPath);
            Debug.LogFormat("CreateAsset: {0}", assetPath);
            AssetDatabase.CreateAsset(meshWithMaterials.Mesh, assetPath);

            // add component
            var meshObject = new GameObject(go.name + ".integrated");
            if (go.transform.parent != null)
            {
                meshObject.transform.SetParent(go.transform.parent, false);
            }
            meshObject.transform.localPosition = go.transform.localPosition;
            meshObject.transform.localRotation = go.transform.localRotation;
            meshObject.transform.localScale    = go.transform.localScale;

            var filter = meshObject.AddComponent <MeshFilter>();
            filter.sharedMesh = meshWithMaterials.Mesh;
            var renderer = meshObject.AddComponent <MeshRenderer>();
            renderer.sharedMaterials = meshWithMaterials.Materials;
        }
示例#7
0
        /// <summary>
        /// Extract images from glb or gltf out of Assets folder.
        /// </summary>
        /// <param name="prefabPath"></param>
        public void ExtractImages(UnityPath prefabPath)
        {
            var prefabParentDir = prefabPath.Parent;

            // glb buffer
            var folder = prefabPath.GetAssetFolder(".Textures");

            //
            // https://answers.unity.com/questions/647615/how-to-update-import-settings-for-newly-created-as.html
            //
            int created = 0;

            //for (int i = 0; i < GLTF.textures.Count; ++i)
            for (int i = 0; i < GLTF.images.Count; ++i)
            {
                folder.EnsureFolder();

                //var x = GLTF.textures[i];
                var image = GLTF.images[i];
                var src   = Storage.GetPath(image.uri);
                if (UnityPath.FromFullpath(src).IsUnderAssetsFolder)
                {
                    // asset is exists.
                }
                else
                {
                    string textureName;
                    var    byteSegment = GLTF.GetImageBytes(Storage, i, out textureName);

                    // path
                    var dst = folder.Child(textureName + image.GetExt());
                    File.WriteAllBytes(dst.FullPath, byteSegment.ToArray());
                    dst.ImportAsset();

                    // make relative path from PrefabParentDir
                    image.uri = dst.Value.Substring(prefabParentDir.Value.Length + 1);
                    ++created;
                }
            }

            if (created > 0)
            {
                AssetDatabase.Refresh();
            }

            CreateTextureItems(prefabParentDir);
        }
示例#8
0
        public static void ImportAsset(string src, string ext, UnityPath prefabPath)
        {
            if (!prefabPath.IsUnderAssetsFolder)
            {
                Debug.LogWarningFormat("out of asset path: {0}", prefabPath);
                return;
            }

            var context = new ImporterContext();

            context.Parse(src);

            // Extract textures to assets folder
            context.ExtractImages(prefabPath);

            ImportDelayed(src, prefabPath, context);
        }
示例#9
0
        static BytesWithMime GetBytesWithMime(Texture texture, glTFTextureTypes textureType)
        {
#if UNITY_EDITOR
            var path = UnityPath.FromAsset(texture);
            if (path.IsUnderAssetsFolder)
            {
                if (path.Extension == ".png")
                {
                    return(new BytesWithMime
                    {
                        Bytes = System.IO.File.ReadAllBytes(path.FullPath),
                        Mime = "image/png",
                    });
                }
            }
#endif

            return(new BytesWithMime
            {
                Bytes = TextureItem.CopyTexture(texture, TextureIO.GetColorSpace(textureType), null).EncodeToPNG(),
                Mime = "image/png",
            });
        }
示例#10
0
        static void CopySRGBWrite(bool isSRGB)
        {
            var src         = Selection.activeObject as Texture;
            var texturePath = UnityPath.FromAsset(src);

            var path = EditorUtility.SaveFilePanel("save prefab", "Assets",
                                                   Path.GetFileNameWithoutExtension(AddPath(texturePath.FullPath, ".sRGB")), "prefab");
            var assetPath = UnityPath.FromFullpath(path);

            if (!assetPath.IsUnderAssetsFolder)
            {
                return;
            }
            Debug.LogFormat("[CopySRGBWrite] {0} => {1}", texturePath, assetPath);

            var renderTexture = new RenderTexture(src.width, src.height, 0,
                                                  RenderTextureFormat.ARGB32,
                                                  RenderTextureReadWrite.sRGB);

            using (var scope = new ColorSpaceScope(isSRGB))
            {
                Graphics.Blit(src, renderTexture);
            }

            var dst = new Texture2D(src.width, src.height, TextureFormat.ARGB32, false,
                                    RenderTextureReadWrite.sRGB == RenderTextureReadWrite.Linear);

            dst.ReadPixels(new Rect(0, 0, src.width, src.height), 0, 0);
            dst.Apply();

            RenderTexture.active = null;

            assetPath.CreateAsset(dst);

            GameObject.DestroyImmediate(renderTexture);
        }
示例#11
0
        public void UnityPathTest()
        {
            var root = UnityPath.FromUnityPath(".");

            Assert.IsFalse(root.IsNull);
            Assert.IsFalse(root.IsUnderAssetsFolder);
            Assert.AreEqual(UnityPath.FromUnityPath("."), root);

            var assets = UnityPath.FromUnityPath("Assets");

            Assert.IsFalse(assets.IsNull);
            Assert.IsTrue(assets.IsUnderAssetsFolder);

            var rootChild = root.Child("Assets");

            Assert.AreEqual(assets, rootChild);

            var assetsChild = assets.Child("Hoge");
            var hoge        = UnityPath.FromUnityPath("Assets/Hoge");

            Assert.AreEqual(assetsChild, hoge);

            //var children = root.TraverseDir().ToArray();
        }
示例#12
0
        public static void ImportMenu()
        {
            var path = EditorUtility.OpenFilePanel("open gltf", "", "gltf,glb,zip");

            if (string.IsNullOrEmpty(path))
            {
                return;
            }

            if (Application.isPlaying)
            {
                //
                // load into scene
                //
                var context = new ImporterContext();
                context.Load(path);
                context.ShowMeshes();
                Selection.activeGameObject = context.Root;
            }
            else
            {
                //
                // save as asset
                //
                if (path.StartsWithUnityAssetPath())
                {
                    Debug.LogWarningFormat("disallow import from folder under the Assets");
                    return;
                }

                var assetPath = EditorUtility.SaveFilePanel("save prefab", "Assets", Path.GetFileNameWithoutExtension(path), "prefab");
                if (string.IsNullOrEmpty(path))
                {
                    return;
                }

                // import as asset
                gltfAssetPostprocessor.ImportAsset(path, Path.GetExtension(path).ToLower(), UnityPath.FromFullpath(assetPath));
            }
        }
示例#13
0
        public void SaveAsAsset(UnityPath prefabPath)
        {
            ShowMeshes();

            //var prefabPath = PrefabPath;
            if (prefabPath.IsFileExists)
            {
                // clear SubAssets
                foreach (var x in prefabPath.GetSubAssets().Where(x => !(x is GameObject) && !(x is Component)))
                {
                    GameObject.DestroyImmediate(x, true);
                }
            }

            //
            // save sub assets
            //
            var paths = new List <UnityPath>()
            {
                prefabPath
            };

            foreach (var o in ObjectsForSubAsset())
            {
                if (o == null)
                {
                    continue;
                }

                var assetPath = GetAssetPath(prefabPath, o);
                if (!assetPath.IsNull)
                {
                    if (assetPath.IsFileExists)
                    {
                        if (AvoidOverwriteAndLoad(assetPath, o))
                        {
                            // 上書きせずに既存のアセットからロードして置き換えた
                            continue;
                        }
                    }

                    // アセットとして書き込む
                    assetPath.Parent.EnsureFolder();
                    assetPath.CreateAsset(o);
                    paths.Add(assetPath);
                }
                else
                {
                    // save as subasset
                    prefabPath.AddObjectToAsset(o);
                }
            }

            // Create or update Main Asset
            if (prefabPath.IsFileExists)
            {
                Debug.LogFormat("replace prefab: {0}", prefabPath);
                var prefab = prefabPath.LoadAsset <GameObject>();
#if UNITY_2018_3_OR_NEWER
                PrefabUtility.SaveAsPrefabAssetAndConnect(Root, prefabPath.Value, InteractionMode.AutomatedAction);
#else
                PrefabUtility.ReplacePrefab(Root, prefab, ReplacePrefabOptions.ReplaceNameBased);
#endif
            }
            else
            {
                Debug.LogFormat("create prefab: {0}", prefabPath);
#if UNITY_2018_3_OR_NEWER
                PrefabUtility.SaveAsPrefabAssetAndConnect(Root, prefabPath.Value, InteractionMode.AutomatedAction);
#else
                PrefabUtility.CreatePrefab(prefabPath.Value, Root);
#endif
            }
            foreach (var x in paths)
            {
                x.ImportAsset();
            }
        }
示例#14
0
 public void ExtranctImages(UnityPath prefabPath)
 {
     ExtractImages(prefabPath);
 }
示例#15
0
 /// <summary>
 /// Texture from asset
 /// </summary>
 /// <param name="index"></param>
 /// <param name="assetPath"></param>
 /// <param name="textureName"></param>
 public TextureItem(int index, UnityPath assetPath, string textureName)
 {
     m_textureIndex  = index;
     IsAsset         = true;
     m_textureLoader = new AssetTextureLoader(assetPath, textureName);
 }
示例#16
0
 public AssetTextureLoader(UnityPath assetPath, string _)
 {
     m_assetPath = assetPath;
 }