Example #1
0
        static void ExtractMaterialsAndTextures(ScriptedImporter self, GltfParser parser, EnumerateAllTexturesDistinctFunc enumTextures, Func <string, string> textureDir, Func <string, string> materialDir)
        {
            if (string.IsNullOrEmpty(self.assetPath))
            {
                return;
            }

            Action <SubAssetKey, Texture2D> addRemap = (key, externalObject) =>
            {
                self.AddRemap(new AssetImporter.SourceAssetIdentifier(key.Type, key.Name), externalObject);
            };
            Action <IEnumerable <UnityPath> > onCompleted = _ =>
            {
                AssetDatabase.ImportAsset(self.assetPath, ImportAssetOptions.ForceUpdate);
                self.ExtractMaterials(materialDir);
                AssetDatabase.ImportAsset(self.assetPath, ImportAssetOptions.ForceUpdate);
            };

            var assetPath = UnityPath.FromFullpath(parser.TargetPath);
            var dirName   = textureDir(assetPath.Value); // $"{assetPath.FileNameWithoutExtension}.Textures";

            TextureExtractor.ExtractTextures(parser, assetPath.Parent.Child(dirName),
                                             enumTextures,
                                             self.GetSubAssets <UnityEngine.Texture2D>(self.assetPath).ToArray(),
                                             addRemap,
                                             onCompleted
                                             );
        }
Example #2
0
        static void ExtractMaterialsAndTextures(ScriptedImporter self, GltfParser parser)
        {
            if (string.IsNullOrEmpty(self.assetPath))
            {
                return;
            }

            Action <Texture2D> addRemap = externalObject =>
            {
                self.AddRemap(new AssetImporter.SourceAssetIdentifier(typeof(UnityEngine.Texture2D), externalObject.name), externalObject);
            };
            Action <IEnumerable <UnityPath> > onCompleted = _ =>
            {
                AssetDatabase.ImportAsset(self.assetPath, ImportAssetOptions.ForceUpdate);
                self.ExtractMaterials();
                AssetDatabase.ImportAsset(self.assetPath, ImportAssetOptions.ForceUpdate);
            };

            var assetPath = UnityPath.FromFullpath(parser.TargetPath);
            var dirName   = $"{assetPath.FileNameWithoutExtension}.Textures";

            TextureExtractor.ExtractTextures(parser, assetPath.Parent.Child(dirName),
                                             GltfTextureEnumerator.Enumerate,
                                             self.GetSubAssets <UnityEngine.Texture2D>(self.assetPath).ToArray(),
                                             addRemap,
                                             onCompleted
                                             );
        }
Example #3
0
        public static ImporterContext Parse(string path, Byte[] bytes)
        {
            var ext     = Path.GetExtension(path).ToLower();
            var context = new ImporterContext(UnityPath.FromFullpath(path));

            switch (ext)
            {
            case ".gltf":
                context.ParseJson(Encoding.UTF8.GetString(bytes), new FileSystemStorage(Path.GetDirectoryName(path)));
                break;

            case ".zip":
            {
                var zipArchive = Zip.ZipArchiveStorage.Parse(bytes);
                var gltf       = zipArchive.Entries.FirstOrDefault(x => x.FileName.ToLower().EndsWith(".gltf"));
                if (gltf == null)
                {
                    throw new Exception("no gltf in archive");
                }
                var jsonBytes = zipArchive.Extract(gltf);
                var json      = Encoding.UTF8.GetString(jsonBytes);
                context.ParseJson(json, zipArchive);
            }
            break;

            case ".glb":
                context.ParseGlb(bytes);
                break;

            default:
                throw new NotImplementedException();
            }
            return(context);
        }
        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;
        }
            public void Dispose()
            {
                // end
                m_w.Write(@"
    } // class
} // namespace
");

                m_w.Dispose();
                m_s.Dispose();
                UnityPath.FromFullpath(m_path).ImportAsset();
            }
        /// <summary>
        /// Extract images from glb or gltf out of Assets folder.
        /// </summary>
        /// <param name="prefabPath"></param>
        public void ExtranctImages(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);
        }
Example #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 < m_context.GLTF.textures.Count; ++i)
            {
                folder.EnsureFolder();

                var gltfTexture = m_context.GLTF.textures[i];
                var gltfImage   = m_context.GLTF.images[gltfTexture.source];
                var src         = m_context.Storage.GetPath(gltfImage.uri);
                if (UnityPath.FromFullpath(src).IsUnderAssetsFolder)
                {
                    // asset is exists.
                }
                else
                {
                    var byteSegment = m_context.GLTF.GetImageBytes(m_context.Storage, gltfTexture.source);
                    var textureName = gltfTexture.name;

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

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

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

            // texture will load from assets
            m_context.TextureFactory.ImageBaseDir = prefabParentDir;
        }
Example #8
0
        static void GenerateSerializer()
        {
            var info = new ObjectSerialization(typeof(glTF), "gltf", "Deserialize_");

            Debug.Log(info);

            using (var s = File.Open(OutPath, FileMode.Create))
                using (var w = new StreamWriter(s, new UTF8Encoding(false)))
                {
                    w.Write(Begin);
                    info.GenerateDeserializer(w, "Deserialize");
                    w.Write(End);
                }

            Debug.LogFormat("write: {0}", OutPath);
            UnityPath.FromFullpath(OutPath).ImportAsset();
        }
Example #9
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);
        }
        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));
            }
        }
Example #11
0
        public static void ImportMenu()
        {
            var path = EditorUtility.OpenFilePanel("open glb", "", "gltf,glb,zip");

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

            if (Application.isPlaying)
            {
                //
                // load into scene
                //
                var data = new AutoGltfFileParser(path).Parse();
                using (var context = new ImporterContext(data))
                {
                    var loaded = context.Load();
                    loaded.ShowMeshes();
                    Selection.activeGameObject = loaded.gameObject;
                }
                return;
            }

            //
            // save as asset
            //
            if (path.StartsWithUnityAssetPath())
            {
                Debug.LogWarningFormat("disallow import from folder under the Assets");
                return;
            }

            var ext       = Path.GetExtension(path).ToLower();
            var assetPath = EditorUtility.SaveFilePanel("save prefab", "Assets", Path.GetFileNameWithoutExtension(path), ext.Substring(1));

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

            // copy
            var bytes = File.ReadAllBytes(path);

            File.WriteAllBytes(assetPath, bytes);
            if (ext == ".gltf")
            {
                // copy associated files
                var src_dir = Path.GetDirectoryName(path);
                var dst_dir = Path.GetDirectoryName(assetPath);
                var data    = new GltfFileWithResourceFilesParser(path, bytes).Parse();
                foreach (var buffer in data.GLTF.buffers)
                {
                    if (!string.IsNullOrEmpty(buffer.uri))
                    {
                        var src_path  = Path.Combine(src_dir, buffer.uri);
                        var src_bytes = File.ReadAllBytes(src_path);
                        var dst_path  = Path.Combine(dst_dir, buffer.uri);
                        File.WriteAllBytes(dst_path, src_bytes);
                        UnityPath.FromFullpath(dst_path).ImportAsset();
                    }
                }
                foreach (var buffer in data.GLTF.images)
                {
                    if (!string.IsNullOrEmpty(buffer.uri))
                    {
                        var src_path  = Path.Combine(src_dir, buffer.uri);
                        var src_bytes = File.ReadAllBytes(src_path);
                        var dst_path  = Path.Combine(dst_dir, buffer.uri);
                        File.WriteAllBytes(dst_path, src_bytes);
                        UnityPath.FromFullpath(dst_path).ImportAsset();
                    }
                }
            }

            // import as asset
            var unitypath = UnityPath.FromFullpath(assetPath);

            unitypath.ImportAsset();
            var asset = unitypath.LoadAsset <GameObject>();

            Selection.activeObject = asset;
        }