예제 #1
0
        /// <summary>
        /// 非同期でByte配列からVRMImporterContextの初期化をします
        /// </summary>
        /// <param name="vrmByteArray"></param>
        public async Task InitializeVrmContextFromByteArrayAsync(byte[] vrmByteArray)
        {
#if UNIVRM_LEGACY_IMPORTER
            // VRMImporterContextがVRMを読み込む機能を提供します
            currentContext = new VRMImporterContext();

            // GLB形式でJSONを取得しParseします
            await Task.Run(() => currentContext.ParseGlb(vrmByteArray));
#elif UNIVRM_0_68_IMPORTER
            var parser = new GltfParser();
            await Task.Run(() => parser.ParseGlb(vrmByteArray));

            currentContext = new VRMImporterContext(parser);
#elif UNIVRM_0_77_IMPORTER
            var      parser = new GlbLowLevelParser(string.Empty, vrmByteArray);
            GltfData data   = null;

            await Task.Run(() =>
            {
                data = parser.Parse();
            });

            currentContext  = new VRMImporterContext(data);
            currentInstance = null;
#else
#endif
        }
예제 #2
0
        /// <summary>
        /// 非同期でByte配列からVRMモデルを読み込む
        /// </summary>
        /// <param name="vrmByteArray"></param>
        /// <returns></returns>
        public async Task <GameObject> LoadVrmModelFromByteArrayAsync(byte[] vrmByteArray)
        {
#if UNIVRM_LEGACY_IMPORTER
            await InitializeVrmContextFromByteArrayAsync(vrmByteArray);

            // 非同期処理(Task)で読み込みます
            await currentContext.LoadAsyncTask();

            // 読込が完了するとcontext.RootにモデルのGameObjectが入っています
            var root = currentContext.Root;

            return(root);
#elif UNIVRM_0_68_IMPORTER
            var parser = new GltfParser();
            await Task.Run(() =>
            {
                parser.ParseGlb(vrmByteArray);
            });

            currentContext = new VRMImporterContext(parser);
            await currentContext.LoadAsync();

            return(currentContext.Root);
#else
            return(null);
#endif
        }
예제 #3
0
        /// <summary>
        /// メタが不要な場合のローダー
        /// </summary>
        async void LoadVRMClicked_without_meta()
        {
#if UNITY_STANDALONE_WIN
            var path = FileDialogForWindows.FileDialog("open VRM", ".vrm");
#elif UNITY_EDITOR
            var path = UnityEditor.EditorUtility.OpenFilePanel("Open VRM", "", "vrm");
#else
            var path = Application.dataPath + "/default.vrm";
#endif
            if (string.IsNullOrEmpty(path))
            {
                return;
            }

            var bytes = File.ReadAllBytes(path);
            // なんらかの方法でByte列を得た

            // GLB形式でJSONを取得しParseします
            var parser = new GltfParser();
            parser.ParseGlb(bytes);

            var context = new VRMImporterContext(parser);
            if (m_loadAsync)
            {
                await context.LoadAsync();
            }
            else
            {
                context.Load();
            }
            OnLoaded(context);
        }
예제 #4
0
        async void OnLoadClicked()
        {
#if UNITY_STANDALONE_WIN
            var path = FileDialogForWindows.FileDialog("open VRM", ".vrm");
#elif UNITY_EDITOR
            var path = UnityEditor.EditorUtility.OpenFilePanel("Open VRM", "", "vrm");
#else
            var path = Application.dataPath + "/default.vrm";
#endif
            if (string.IsNullOrEmpty(path))
            {
                return;
            }

            var bytes = File.ReadAllBytes(path);
            // なんらかの方法でByte列を得た

            // GLB形式でJSONを取得しParseします
            var parser = new GltfParser();
            parser.ParseGlb(bytes);

            using (var context = new VRMImporterContext(parser))
            {
                // metaを取得(todo: thumbnailテクスチャのロード)
                var meta = await context.ReadMetaAsync();

                Debug.LogFormat("meta: title:{0}", meta.Title);

                // ParseしたJSONをシーンオブジェクトに変換していく
                await context.LoadAsync();

                OnLoaded(context);
            }
        }
예제 #5
0
        public void SerializerCompare()
        {
            // Aliciaを古いデシリアライザでロードする
            var path   = AliciaPath;
            var parser = new GltfParser();

            parser.ParseGlb(File.ReadAllBytes(path));

            using (var context = new VRMImporterContext(parser))
            {
                var oldJson = context.GLTF.ToJson().ParseAsJson().ToString("  ");

                // 生成シリアライザでJSON化する
                var f = new JsonFormatter();
                GltfSerializer.Serialize(f, context.GLTF);
                var parsed  = f.ToString().ParseAsJson();
                var newJson = parsed.ToString("  ");

                // File.WriteAllText("old.json", oldJson);
                // File.WriteAllText("new.json", newJson);

                // 比較
                Assert.AreEqual(oldJson.ParseAsJson().ToString(), newJson.ParseAsJson().ToString());

                // 生成デシリアライザでロードする
                var ff  = new JsonFormatter();
                var des = GltfDeserializer.Deserialize(parsed);
                ff.Clear();
                GltfSerializer.Serialize(ff, des);
                var desJson = ff.ToString().ParseAsJson().ToString("  ");
                Assert.AreEqual(oldJson.ParseAsJson().ToString(), desJson.ParseAsJson().ToString());
            }
        }
예제 #6
0
        /// <summary>
        /// 同期でByte配列からVRMモデルを読み込む
        /// </summary>
        /// <param name="vrmByteArray"></param>
        /// <returns></returns>
        public GameObject LoadVrmModelFromByteArray(byte[] vrmByteArray)
        {
#if UNIVRM_LEGACY_IMPORTER
            InitializeVrmContextFromByteArray(vrmByteArray);

            // 同期処理で読み込みます
            currentContext.Load();

            // 読込が完了するとcontext.RootにモデルのGameObjectが入っています
            var root = currentContext.Root;

            return(root);
#elif UNIVRM_0_68_IMPORTER
            var parser = new GltfParser();
            parser.ParseGlb(vrmByteArray);

            currentContext = new VRMImporterContext(parser);
            currentContext.Load();

            return(currentContext.Root);
#elif UNIVRM_0_77_IMPORTER
            var parser = new GlbLowLevelParser(string.Empty, vrmByteArray);
            var data   = parser.Parse();

            currentContext  = new VRMImporterContext(data);
            currentInstance = currentContext.Load();

            return(currentInstance.Root);
#else
            return(null);
#endif
        }
예제 #7
0
        static void ImportMenu()
        {
            var path = EditorUtility.OpenFilePanel("open vrm", "", "vrm");

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

            if (Application.isPlaying)
            {
                // load into scene
                var parser = new GltfParser();
                parser.ParsePath(path);

                using (var context = new VRMImporterContext(parser))
                {
                    context.Load();
                    context.EnableUpdateWhenOffscreen();
                    context.ShowMeshes();
                    context.DisposeOnGameObjectDestroyed();
                    Selection.activeGameObject = context.Root;
                }
            }
            else
            {
                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;
                }

                if (!assetPath.StartsWithUnityAssetPath())
                {
                    Debug.LogWarningFormat("out of asset path: {0}", assetPath);
                    return;
                }

                // import as asset
                var prefabPath = UnityPath.FromUnityPath(assetPath);
                var parser     = new GltfParser();
                parser.ParseGlb(File.ReadAllBytes(path));

                Action <IEnumerable <string> > onCompleted = texturePaths =>
                {
                    //
                    // after textures imported
                    //
                    var map = texturePaths.Select(x =>
                    {
                        var texture = AssetDatabase.LoadAssetAtPath(x, typeof(Texture2D));
                        return(texture.name, texture);
                    }).ToArray();
예제 #8
0
        static void ImportMenu()
        {
            var path = EditorUtility.OpenFilePanel("open vrm", "", "vrm");

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

            if (Application.isPlaying)
            {
                // load into scene
                var parser = new GltfParser();
                parser.ParsePath(path);
                var context = new VRMImporterContext(parser);
                context.Load();
                context.ShowMeshes();
                context.EnableUpdateWhenOffscreen();
                Selection.activeGameObject = context.Root;
            }
            else
            {
                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;
                }

                if (!assetPath.StartsWithUnityAssetPath())
                {
                    Debug.LogWarningFormat("out of asset path: {0}", assetPath);
                    return;
                }

                // import as asset
                var prefabPath = UnityPath.FromUnityPath(assetPath);
                var parser     = new GltfParser();
                parser.ParseGlb(File.ReadAllBytes(path));
                var context = new VRMImporterContext(parser);
                var editor  = new VRMEditorImporterContext(context);
                editor.ExtractImages(prefabPath);

                EditorApplication.delayCall += () =>
                {
                    //
                    // after textures imported
                    //
                    context.Load();
                    editor.SaveAsAsset(prefabPath);
                    editor.Dispose();
                };
            }
        }
예제 #9
0
        /// <summary>
        /// Byte配列からVRMImporterContextの初期化をします
        /// </summary>
        /// <param name="vrmByteArray"></param>
        public void InitializeVrmContextFromByteArray(byte[] vrmByteArray)
        {
#if UNIVRM_LEGACY_IMPORTER
            // VRMImporterContextがVRMを読み込む機能を提供します
            currentContext = new VRMImporterContext();

            // GLB形式でJSONを取得しParseします
            currentContext.ParseGlb(vrmByteArray);
#elif UNIVRM_0_68_IMPORTER
            var parser = new GltfParser();
            parser.ParseGlb(vrmByteArray);
            currentContext = new VRMImporterContext(parser);
#else
#endif
        }
예제 #10
0
        /// <summary>
        /// 非同期でByte配列からVRMImporterContextの初期化をします
        /// </summary>
        /// <param name="vrmByteArray"></param>
        public async Task InitializeVrmContextFromByteArrayAsync(byte[] vrmByteArray)
        {
#if UNIVRM_LEGACY_IMPORTER
            // VRMImporterContextがVRMを読み込む機能を提供します
            currentContext = new VRMImporterContext();

            // GLB形式でJSONを取得しParseします
            await Task.Run(() => currentContext.ParseGlb(vrmByteArray));
#elif UNIVRM_0_68_IMPORTER
            var parser = new GltfParser();
            await Task.Run(() => parser.ParseGlb(vrmByteArray));

            currentContext = new VRMImporterContext(parser);
#else
#endif
        }
예제 #11
0
        static void ImportVrm(UnityPath path)
        {
            if (!path.IsUnderAssetsFolder)
            {
                throw new Exception();
            }

            var parser = new GltfParser();

            try
            {
                parser.ParseGlb(File.ReadAllBytes(path.FullPath));
            }
            catch (KeyNotFoundException)
            {
                // invalid VRM-0.X.
                // maybe VRM-1.0.do nothing
                return;
            }

            var prefabPath = path.Parent.Child(path.FileNameWithoutExtension + ".prefab");

            // save texture assets !
            LoadTextureAsyncFunc textureLoader = async(caller, textureIndex, used) =>
            {
                var gltfTexture = parser.GLTF.textures[textureIndex];
                var gltfImage   = parser.GLTF.images[gltfTexture.source];
                var assetPath   = prefabPath.Parent.Child(gltfImage.uri);
                var texture     = await UniGLTF.AssetTextureLoader.LoadTaskAsync(assetPath, parser.GLTF, textureIndex);

                return(new TextureLoadInfo(texture, used, false));
            };
            var context = new VRMImporterContext(parser, textureLoader);
            var editor  = new VRMEditorImporterContext(context);

            editor.ExtractImages(prefabPath);

            EditorApplication.delayCall += () =>
            {
                //
                // after textures imported
                //
                context.Load();
                editor.SaveAsAsset(prefabPath);
                editor.Dispose();
            };
        }
예제 #12
0
        public void MeshCopyTest()
        {
            var path   = AliciaPath;
            var parser = new GltfParser();

            parser.ParseGlb(File.ReadAllBytes(path));
            var context = new VRMImporterContext(parser);

            context.Load();
            context.ShowMeshes();
            context.EnableUpdateWhenOffscreen();

            foreach (var mesh in context.Meshes)
            {
                var src = mesh.Mesh;
                var dst = src.Copy(true);
                MeshTests.MeshEquals(src, dst);
            }
        }
예제 #13
0
        static void ImportVrm(UnityPath path)
        {
            if (!path.IsUnderAssetsFolder)
            {
                throw new Exception();
            }

            var parser = new GltfParser();

            parser.ParseGlb(File.ReadAllBytes(path.FullPath));

            var prefabPath = path.Parent.Child(path.FileNameWithoutExtension + ".prefab");

            Action <IEnumerable <string> > onCompleted = texturePaths =>
            {
                var map = texturePaths.Select(x =>
                {
                    var texture = AssetDatabase.LoadAssetAtPath(x, typeof(Texture2D));
                    return(texture.name, texture);
                }).ToArray();
예제 #14
0
        static void ImportVrm(UnityPath vrmPath)
        {
            if (!vrmPath.IsUnderAssetsFolder)
            {
                throw new Exception();
            }

            var parser = new GltfParser();

            parser.ParseGlb(File.ReadAllBytes(vrmPath.FullPath));

            var prefabPath = vrmPath.Parent.Child(vrmPath.FileNameWithoutExtension + ".prefab");

            Action <IEnumerable <UnityPath> > onCompleted = texturePaths =>
            {
                var map = texturePaths.Select(x =>
                {
                    var texture = x.LoadAsset <Texture2D>();
                    return(texture.name, texture: texture as UnityEngine.Object);
                }).ToArray();
예제 #15
0
        static void ImportVrm(UnityPath path)
        {
            if (!path.IsUnderAssetsFolder)
            {
                throw new Exception();
            }

            var parser = new GltfParser();

            try
            {
                parser.ParseGlb(File.ReadAllBytes(path.FullPath));
            }
            catch (KeyNotFoundException)
            {
                // invalid VRM-0.X.
                // maybe VRM-1.0.do nothing
                return;
            }

            var prefabPath = path.Parent.Child(path.FileNameWithoutExtension + ".prefab");

            // save texture assets !
            var context = new VRMImporterContext(parser);

            context.ExtractImages(prefabPath);

            EditorApplication.delayCall += () =>
            {
                //
                // after textures imported
                //
                context.Load();
                context.SaveAsAsset(prefabPath);
                context.EditorDestroyRoot();
            };
        }
예제 #16
0
        static void ImportAsset(string path, UnityPath prefabPath)
        {
            if (!prefabPath.IsUnderAssetsFolder)
            {
                Debug.LogWarningFormat("out of asset path: {0}", prefabPath);
                return;
            }

            // import as asset
            // var prefabPath = UnityPath.FromUnityPath(prefabPath);
            var parser = new GltfParser();

            parser.ParseGlb(File.ReadAllBytes(path));

            Action <IEnumerable <UnityPath> > onCompleted = texturePaths =>
            {
                //
                // after textures imported
                //
                var map = texturePaths.Select(x =>
                {
                    var texture = x.LoadAsset <Texture2D>() as UnityEngine.Object;
                    return(texture.name, texture);
                }).ToArray();
예제 #17
0
        public void ImportExportTest()
        {
            var path   = AliciaPath;
            var parser = new GltfParser();

            parser.ParseGlb(File.ReadAllBytes(path));

            using (var context = new VRMImporterContext(parser))
            {
                context.Load();
                context.ShowMeshes();
                context.EnableUpdateWhenOffscreen();

                var importedJson = JsonParser.Parse(context.Json);
                importedJson.SetValue("/extensions/VRM/exporterVersion", VRMVersion.VRM_VERSION, (f, x) => f.Value(x));
                importedJson.SetValue("/asset/generator", UniGLTF.UniGLTFVersion.UNIGLTF_VERSION, (f, x) => f.Value(x));
                importedJson.SetValue("/scene", 0, (f, x) => f.Value(x));
                importedJson.SetValue("/materials/*/doubleSided", false, (f, x) => f.Value(x));
                //importJson.SetValue("/materials/*/pbrMetallicRoughness/roughnessFactor", 0);
                //importJson.SetValue("/materials/*/pbrMetallicRoughness/baseColorFactor", new float[] { 1, 1, 1, 1 });
                importedJson.SetValue("/accessors/*/normalized", false, (f, x) => f.Value(x));
                importedJson.RemoveValue(Utf8String.From("/nodes/*/extras"));

                /*
                 * importJson.SetValue("/bufferViews/12/byteStride", 4);
                 * importJson.SetValue("/bufferViews/13/byteStride", 4);
                 * importJson.SetValue("/bufferViews/14/byteStride", 4);
                 * importJson.SetValue("/bufferViews/15/byteStride", 4);
                 * importJson.SetValue("/bufferViews/22/byteStride", 4);
                 * importJson.SetValue("/bufferViews/29/byteStride", 4);
                 * importJson.SetValue("/bufferViews/45/byteStride", 4);
                 * importJson.SetValue("/bufferViews/46/byteStride", 4);
                 * importJson.SetValue("/bufferViews/47/byteStride", 4);
                 * importJson.SetValue("/bufferViews/201/byteStride", 4);
                 * importJson.SetValue("/bufferViews/202/byteStride", 4);
                 * importJson.SetValue("/bufferViews/203/byteStride", 4);
                 * importJson.SetValue("/bufferViews/204/byteStride", 4);
                 * importJson.SetValue("/bufferViews/211/byteStride", 4);
                 * importJson.SetValue("/bufferViews/212/byteStride", 4);
                 * importJson.SetValue("/bufferViews/213/byteStride", 4);
                 * importJson.SetValue("/bufferViews/214/byteStride", 4);
                 * importJson.SetValue("/bufferViews/215/byteStride", 4);
                 * importJson.SetValue("/bufferViews/243/byteStride", 4);
                 * importJson.SetValue("/bufferViews/247/byteStride", 64);
                 * importJson.SetValue("/bufferViews/248/byteStride", 64);
                 * importJson.SetValue("/bufferViews/249/byteStride", 64);
                 * importJson.SetValue("/bufferViews/250/byteStride", 64);
                 * importJson.SetValue("/bufferViews/251/byteStride", 64);
                 * importJson.SetValue("/bufferViews/252/byteStride", 64);
                 * importJson.SetValue("/bufferViews/253/byteStride", 64);
                 */
                importedJson.RemoveValue(Utf8String.From("/bufferViews/*/byteStride"));

                var vrm = VRMExporter.Export(UniGLTF.MeshExportSettings.Default, context.Root);

                // TODO: Check contents in JSON
                /*var exportJson = */
                JsonParser.Parse(vrm.ToJson());

                // TODO: Check contents in JSON
                /*var newExportedJson = */
                // JsonParser.Parse(JsonSchema.FromType<glTF>().Serialize(vrm));

                /*
                 * foreach (var kv in importJson.Diff(exportJson))
                 * {
                 *  Debug.Log(kv);
                 * }
                 *
                 * Assert.AreEqual(importJson, exportJson);
                 */
            }
        }
예제 #18
0
파일: ViewerUI.cs 프로젝트: pdkyll/UniVRM
        void LoadModel(string path)
        {
            if (!File.Exists(path))
            {
                return;
            }

            Debug.LogFormat("{0}", path);
            var ext = Path.GetExtension(path).ToLower();

            switch (ext)
            {
            case ".vrm":
            {
                // var context = new ImporterContext();
                var file = File.ReadAllBytes(path);
                // context.ParseGlb(file);
                // context.Load();
                // context.ShowMeshes();
                // context.EnableUpdateWhenOffscreen();
                // context.ShowMeshes();

                var model = UniVRM10.VrmLoader.CreateVrmModel(file, new FileInfo(path));

                // UniVRM-0.XXのコンポーネントを構築する
                var assets = UniVRM10.RuntimeUnityBuilder.ToUnityAsset(model, showMesh: false);

                // showRenderer = false のときに後で表示する例
                foreach (var renderer in assets.Renderers)
                {
                    renderer.enabled = true;
                }

                UniVRM10.ComponentBuilder.Build10(model, assets);

                SetModel(assets.Root);
                break;
            }

            case ".glb":
            {
                var file   = File.ReadAllBytes(path);
                var parser = new GltfParser();
                parser.ParseGlb(file);

                var context = new UniGLTF.ImporterContext(parser);
                context.Load();
                context.ShowMeshes();
                context.EnableUpdateWhenOffscreen();
                context.ShowMeshes();
                SetModel(context.Root);
                break;
            }

            case ".gltf":
            case ".zip":
            {
                var parser = new GltfParser();
                parser.ParsePath(path);

                var context = new UniGLTF.ImporterContext(parser);
                context.Load();
                context.ShowMeshes();
                context.EnableUpdateWhenOffscreen();
                context.ShowMeshes();
                SetModel(context.Root);
                break;
            }

            default:
                Debug.LogWarningFormat("unknown file type: {0}", path);
                break;
            }
        }
예제 #19
0
        void LoadModel(string path)
        {
            if (!File.Exists(path))
            {
                return;
            }

            Debug.LogFormat("{0}", path);
            var ext = Path.GetExtension(path).ToLower();

            switch (ext)
            {
            case ".vrm":
            {
                var parser = new UniGLTF.GltfParser();
                parser.ParsePath(path);

                using (var loader = new RuntimeUnityBuilder(parser))
                {
                    loader.Load();
                    loader.ShowMeshes();
                    loader.EnableUpdateWhenOffscreen();
                    var destroyer = loader.DisposeOnGameObjectDestroyed();
                    SetModel(destroyer.gameObject);
                }
                break;
            }

            case ".glb":
            {
                var file   = File.ReadAllBytes(path);
                var parser = new GltfParser();
                parser.ParseGlb(file);

                using (var loader = new UniGLTF.ImporterContext(parser))
                {
                    loader.Load();
                    loader.ShowMeshes();
                    loader.EnableUpdateWhenOffscreen();
                    loader.ShowMeshes();
                    var destroyer = loader.DisposeOnGameObjectDestroyed();
                    SetModel(destroyer.gameObject);
                }
                break;
            }

            case ".gltf":
            case ".zip":
            {
                var parser = new GltfParser();
                parser.ParsePath(path);

                using (var loader = new UniGLTF.ImporterContext(parser))
                {
                    loader.Load();
                    loader.ShowMeshes();
                    loader.EnableUpdateWhenOffscreen();
                    loader.ShowMeshes();
                    var destroyer = loader.DisposeOnGameObjectDestroyed();
                    SetModel(destroyer.gameObject);
                }
                break;
            }

            default:
                Debug.LogWarningFormat("unknown file type: {0}", path);
                break;
            }
        }
예제 #20
0
        public void ImportExportTest()
        {
            var path   = AliciaPath;
            var parser = new GltfParser();

            parser.ParseGlb(File.ReadAllBytes(path));

            using (var context = new VRMImporterContext(parser))
            {
                context.Load();
                context.ShowMeshes();
                context.EnableUpdateWhenOffscreen();

                var destroyer = context.DisposeOnGameObjectDestroyed();
                try
                {
                    // mesh
                    {
                        foreach (var renderer in destroyer.GetComponentsInChildren <Renderer>())
                        {
                            Mesh mesh = default;
                            if (renderer is MeshRenderer)
                            {
                                var f = renderer.GetComponent <MeshFilter>();
                                mesh = f.sharedMesh;
                            }
                            else if (renderer is SkinnedMeshRenderer smr)
                            {
                                mesh = smr.sharedMesh;
                            }

                            var gltfMesh = parser.GLTF.meshes.Find(x => x.name == mesh.name);
                            Assert.AreEqual(gltfMesh.name, mesh.name);

                            // materials
                            foreach (var material in renderer.sharedMaterials)
                            {
                                var gltfMaterial = parser.GLTF.materials.Find(x => x.name == material.name);
                                Assert.AreEqual(gltfMaterial.name, material.name);

                                var materialIndex = parser.GLTF.materials.IndexOf(gltfMaterial);
                                var vrmMaterial   = context.VRM.materialProperties[materialIndex];
                                // Debug.Log($"shaderName: '{vrmMaterial.shader}'");
                                if (vrmMaterial.shader == "VRM/MToon")
                                {
                                    // MToon
                                    // Debug.Log($"{material.name} is MToon");
                                    foreach (var kv in vrmMaterial.textureProperties)
                                    {
                                        var texture = material.GetTexture(kv.Key);
                                        // Debug.Log($"{kv.Key}: {texture}");
                                        Assert.NotNull(texture);
                                    }
                                }
                                else if (glTF_KHR_materials_unlit.IsEnable(gltfMaterial))
                                {
                                    // Unlit
                                    // Debug.Log($"{material.name} is unlit");
                                    throw new NotImplementedException();
                                }
                                else
                                {
                                    // PBR
                                    // Debug.Log($"{material.name} is PBR");
                                    throw new NotImplementedException();
                                }
                            }
                        }
                    }

                    // meta
                    {
                        var meta = destroyer.GetComponent <VRMMeta>();
                    }

                    // humanoid
                    {
                        var animator = destroyer.GetComponent <Animator>();
                    }


                    // blendshape
                    {
                        var blendshapeProxy = destroyer.GetComponent <VRMBlendShapeProxy>();
                        for (int i = 0; i < context.VRM.blendShapeMaster.blendShapeGroups.Count; ++i)
                        {
                            var gltfBlendShapeClip  = context.VRM.blendShapeMaster.blendShapeGroups[i];
                            var unityBlendShapeClip = blendshapeProxy.BlendShapeAvatar.Clips[i];
                            Assert.AreEqual(Enum.Parse(typeof(BlendShapePreset), gltfBlendShapeClip.presetName, true), unityBlendShapeClip.Preset);
                        }
                    }

                    var importedJson = JsonParser.Parse(context.Json);
                    importedJson.SetValue("/extensions/VRM/exporterVersion", VRMVersion.VRM_VERSION, (f, x) => f.Value(x));
                    importedJson.SetValue("/asset/generator", UniGLTF.UniGLTFVersion.UNIGLTF_VERSION, (f, x) => f.Value(x));
                    importedJson.SetValue("/scene", 0, (f, x) => f.Value(x));
                    importedJson.SetValue("/materials/*/doubleSided", false, (f, x) => f.Value(x));
                    //importJson.SetValue("/materials/*/pbrMetallicRoughness/roughnessFactor", 0);
                    //importJson.SetValue("/materials/*/pbrMetallicRoughness/baseColorFactor", new float[] { 1, 1, 1, 1 });
                    importedJson.SetValue("/accessors/*/normalized", false, (f, x) => f.Value(x));
                    importedJson.RemoveValue(Utf8String.From("/nodes/*/extras"));

                    /*
                     * importJson.SetValue("/bufferViews/12/byteStride", 4);
                     * importJson.SetValue("/bufferViews/13/byteStride", 4);
                     * importJson.SetValue("/bufferViews/14/byteStride", 4);
                     * importJson.SetValue("/bufferViews/15/byteStride", 4);
                     * importJson.SetValue("/bufferViews/22/byteStride", 4);
                     * importJson.SetValue("/bufferViews/29/byteStride", 4);
                     * importJson.SetValue("/bufferViews/45/byteStride", 4);
                     * importJson.SetValue("/bufferViews/46/byteStride", 4);
                     * importJson.SetValue("/bufferViews/47/byteStride", 4);
                     * importJson.SetValue("/bufferViews/201/byteStride", 4);
                     * importJson.SetValue("/bufferViews/202/byteStride", 4);
                     * importJson.SetValue("/bufferViews/203/byteStride", 4);
                     * importJson.SetValue("/bufferViews/204/byteStride", 4);
                     * importJson.SetValue("/bufferViews/211/byteStride", 4);
                     * importJson.SetValue("/bufferViews/212/byteStride", 4);
                     * importJson.SetValue("/bufferViews/213/byteStride", 4);
                     * importJson.SetValue("/bufferViews/214/byteStride", 4);
                     * importJson.SetValue("/bufferViews/215/byteStride", 4);
                     * importJson.SetValue("/bufferViews/243/byteStride", 4);
                     * importJson.SetValue("/bufferViews/247/byteStride", 64);
                     * importJson.SetValue("/bufferViews/248/byteStride", 64);
                     * importJson.SetValue("/bufferViews/249/byteStride", 64);
                     * importJson.SetValue("/bufferViews/250/byteStride", 64);
                     * importJson.SetValue("/bufferViews/251/byteStride", 64);
                     * importJson.SetValue("/bufferViews/252/byteStride", 64);
                     * importJson.SetValue("/bufferViews/253/byteStride", 64);
                     */
                    importedJson.RemoveValue(Utf8String.From("/bufferViews/*/byteStride"));

                    var vrm = VRMExporter.Export(UniGLTF.MeshExportSettings.Default, context.Root, new EditorTextureSerializer());

                    // TODO: Check contents in JSON
                    /*var exportJson = */
                    JsonParser.Parse(vrm.ToJson());

                    // TODO: Check contents in JSON
                    /*var newExportedJson = */
                    // JsonParser.Parse(JsonSchema.FromType<glTF>().Serialize(vrm));

                    /*
                     * foreach (var kv in importJson.Diff(exportJson))
                     * {
                     *  Debug.Log(kv);
                     * }
                     *
                     * Assert.AreEqual(importJson, exportJson);
                     */
                }
                finally
                {
                    UnityEngine.Object.DestroyImmediate(destroyer.gameObject);
                }
            }
        }
예제 #21
0
        async void LoadModelAsync(string path)
        {
            if (!File.Exists(path))
            {
                return;
            }

            Debug.LogFormat("{0}", path);
            var ext = Path.GetExtension(path).ToLower();

            switch (ext)
            {
            case ".vrm":
            {
                var file = File.ReadAllBytes(path);

                var parser = new GltfParser();
                parser.ParseGlb(file);

                using (var context = new VRMImporterContext(parser))
                {
                    await m_texts.UpdateMetaAsync(context);

                    await context.LoadAsync();

                    context.EnableUpdateWhenOffscreen();
                    context.ShowMeshes();
                    context.DisposeOnGameObjectDestroyed();
                    SetModel(context.Root);
                }
                break;
            }

            case ".glb":
            {
                var file   = File.ReadAllBytes(path);
                var parser = new GltfParser();
                parser.ParseGlb(file);

                var context = new UniGLTF.ImporterContext(parser);
                context.Load();
                context.EnableUpdateWhenOffscreen();
                context.ShowMeshes();
                context.DisposeOnGameObjectDestroyed();
                SetModel(context.Root);
                break;
            }

            case ".gltf":
            case ".zip":
            {
                var parser = new GltfParser();
                parser.ParsePath(path);

                var context = new UniGLTF.ImporterContext(parser);
                context.Load();
                context.EnableUpdateWhenOffscreen();
                context.ShowMeshes();
                context.DisposeOnGameObjectDestroyed();
                SetModel(context.Root);
                break;
            }

            default:
                Debug.LogWarningFormat("unknown file type: {0}", path);
                break;
            }
        }