diff --git a/Assets/UniGLTF/Editor/EditorImporterContext.cs b/Assets/UniGLTF/Editor/EditorImporterContext.cs
deleted file mode 100644
index 33197de02..000000000
--- a/Assets/UniGLTF/Editor/EditorImporterContext.cs
+++ /dev/null
@@ -1,249 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using UnityEditor;
-using UnityEngine;
-
-
-namespace UniGLTF
-{
- ///
- /// Editor で Asset 化する場合専用
- ///
- /// GameObject を prefab 化するので、prefab の元になった GameObject は破棄対象となる。
- ///
- ///
- public class EditorImporterContext : IDisposable
- {
- ImporterContext m_context;
-
- public EditorImporterContext(ImporterContext context)
- {
- m_context = context;
- }
-
- public void Dispose()
- {
- m_context.Dispose();
-
- if (m_context.Root != null)
- {
- // Destroy the GameObject that became the basis of Prefab
- GameObject.DestroyImmediate(m_context.Root);
- }
- }
-
- public virtual IEnumerable ObjectsForSubAsset()
- {
- foreach (var x in m_context.TextureFactory.ObjectsForSubAsset())
- {
- yield return x;
- }
- foreach (var x in m_context.MaterialFactory.ObjectsForSubAsset())
- {
- yield return x;
- }
- foreach (var x in m_context.Meshes) { yield return x.Mesh; }
- foreach (var x in m_context.AnimationClips) { yield return x; }
- }
-
- ///
- /// Destroy assets that created ImporterContext. This function is clean up for importer error.
- ///
- public virtual void EditorDestroyRootAndAssets()
- {
- // Remove hierarchy
- if (m_context.Root != null) GameObject.DestroyImmediate(m_context.Root);
-
- // Remove resources. materials, textures meshes etc...
- foreach (var o in ObjectsForSubAsset())
- {
- UnityEngine.Object.DestroyImmediate(o, true);
- }
- }
-
- public virtual UnityPath GetAssetPath(UnityPath prefabPath, UnityEngine.Object o, bool meshAsSubAsset)
- {
- 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);
- }
- }
-
- public virtual bool AvoidOverwriteAndLoad(UnityPath assetPath, UnityEngine.Object o)
- {
- if (o is Material)
- {
- var loaded = assetPath.LoadAsset();
-
- // replace component reference
- foreach (var mesh in m_context.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;
- }
-
- public void SaveAsAsset(UnityPath prefabPath, bool meshAsSubAsset = false)
- {
- m_context.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(){
- prefabPath
- };
- foreach (var o in ObjectsForSubAsset())
- {
- if (!string.IsNullOrEmpty(AssetDatabase.GetAssetPath(o)))
- {
- // already exists
- continue;
- }
-
- var assetPath = GetAssetPath(prefabPath, o, meshAsSubAsset);
- 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();
-#if UNITY_2018_3_OR_NEWER
- PrefabUtility.SaveAsPrefabAssetAndConnect(m_context.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(m_context.Root, prefabPath.Value, InteractionMode.AutomatedAction);
-#else
- PrefabUtility.CreatePrefab(prefabPath.Value, Root);
-#endif
- }
- foreach (var x in paths)
- {
- x.ImportAsset();
- }
- }
-
- ///
- /// Extract images from glb or gltf out of Assets folder.
- ///
- ///
- 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;
- }
- }
-}
diff --git a/Assets/UniGLTF/Editor/UniGLTF/ImporterMenu.cs b/Assets/UniGLTF/Editor/UniGLTF/ImporterMenu.cs
deleted file mode 100644
index 30d799abc..000000000
--- a/Assets/UniGLTF/Editor/UniGLTF/ImporterMenu.cs
+++ /dev/null
@@ -1,55 +0,0 @@
-#if false
-using System.IO;
-using UnityEditor;
-using UnityEngine;
-
-
-namespace UniGLTF
-{
- public static class ImporterMenu
- {
- [MenuItem(UniGLTFVersion.MENU + "/Import(gltf, glb)", priority = 20)]
- public static void ImportMenu()
- {
- var path = EditorUtility.OpenFilePanel("open gltf", "", "gltf,glb");
- if (string.IsNullOrEmpty(path))
- {
- return;
- }
-
- if (Application.isPlaying)
- {
- //
- // load into scene
- //
- var parser = new GltfParser();
- parser.ParsePath(path);
- var context = new ImporterContext(parser);
- context.Load();
- 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));
- }
- }
- }
-}
-#endif
\ No newline at end of file
diff --git a/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/EditorAnimation.cs b/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/EditorAnimation.cs
new file mode 100644
index 000000000..821939c3d
--- /dev/null
+++ b/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/EditorAnimation.cs
@@ -0,0 +1,16 @@
+using UnityEngine;
+
+namespace UniGLTF
+{
+ public static class EditorAnimation
+ {
+ public static void OnGUIAnimation(GltfParser parser)
+ {
+ for (int i = 0; i < parser.GLTF.animations.Count; ++i)
+ {
+ var a = parser.GLTF.animations[i];
+ GUILayout.Label($"{i}: {a.name}");
+ }
+ }
+ }
+}
diff --git a/Assets/UniGLTF/Editor/EditorImporterContext.cs.meta b/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/EditorAnimation.cs.meta
similarity index 83%
rename from Assets/UniGLTF/Editor/EditorImporterContext.cs.meta
rename to Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/EditorAnimation.cs.meta
index bb14f8f6b..c426102d8 100644
--- a/Assets/UniGLTF/Editor/EditorImporterContext.cs.meta
+++ b/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/EditorAnimation.cs.meta
@@ -1,5 +1,5 @@
fileFormatVersion: 2
-guid: 1c496f43ae12f9041a16af0489727587
+guid: 005298fbae4759b4896174bb6e129e9d
MonoImporter:
externalObjects: {}
serializedVersion: 2
diff --git a/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/EditorMaterial.cs b/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/EditorMaterial.cs
new file mode 100644
index 000000000..294b875a7
--- /dev/null
+++ b/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/EditorMaterial.cs
@@ -0,0 +1,156 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using UnityEditor;
+using UnityEditor.Experimental.AssetImporters;
+using UnityEngine;
+
+namespace UniGLTF
+{
+ public static class EditorMaterial
+ {
+ class TmpGuiEnable : IDisposable
+ {
+ bool m_backup;
+ public TmpGuiEnable(bool enable)
+ {
+ m_backup = GUI.enabled;
+ GUI.enabled = enable;
+ }
+
+ public void Dispose()
+ {
+ GUI.enabled = m_backup;
+ }
+ }
+
+ static bool s_foldMaterials;
+ static bool s_foldTextures;
+
+ public static void OnGUIMaterial(ScriptedImporter importer, GltfParser parser)
+ {
+ var canExtract = !importer.GetExternalObjectMap().Any(x => x.Value is Material || x.Value is Texture2D);
+ using (new TmpGuiEnable(canExtract))
+ {
+ if (GUILayout.Button("Extract Materials And Textures ..."))
+ {
+ ExtractMaterialsAndTextures(importer);
+ }
+ }
+
+ //
+ // Draw ExternalObjectMap
+ //
+ s_foldMaterials = EditorGUILayout.Foldout(s_foldMaterials, "Remapped Materials");
+ if (s_foldMaterials)
+ {
+ DrawRemapGUI(importer, parser.GLTF.materials.Select(x => x.name));
+ }
+
+ s_foldTextures = EditorGUILayout.Foldout(s_foldTextures, "Remapped Textures");
+ if (s_foldTextures)
+ {
+ DrawRemapGUI(importer, parser.EnumerateTextures().Select(x => x.ConvertedName));
+ }
+
+ if (GUILayout.Button("Clear"))
+ {
+ importer.ClearExternalObjects();
+ importer.ClearExternalObjects();
+ }
+ }
+
+ static void DrawRemapGUI(ScriptedImporter importer, IEnumerable names) where T : UnityEngine.Object
+ {
+ EditorGUI.indentLevel++;
+ var map = importer.GetExternalObjectMap()
+ .Select(x => (x.Key.name, x.Value as T))
+ .Where(x => x.Item2 != null)
+ .ToDictionary(x => x.Item1, x => x.Item2)
+ ;
+ foreach (var name in names)
+ {
+ if (string.IsNullOrEmpty(name))
+ {
+ throw new System.ArgumentNullException();
+ }
+
+ EditorGUILayout.BeginHorizontal();
+ EditorGUILayout.PrefixLabel(name);
+ map.TryGetValue(name, out T value);
+ var asset = EditorGUILayout.ObjectField(value, typeof(T), true) as T;
+ if (asset != value)
+ {
+ importer.SetExternalUnityObject(new AssetImporter.SourceAssetIdentifier(value), asset);
+ }
+ EditorGUILayout.EndHorizontal();
+ }
+ EditorGUI.indentLevel--;
+ }
+
+ public static void SetExternalUnityObject(this ScriptedImporter self, UnityEditor.AssetImporter.SourceAssetIdentifier sourceAssetIdentifier, T obj) where T : UnityEngine.Object
+ {
+ self.AddRemap(sourceAssetIdentifier, obj);
+ AssetDatabase.WriteImportSettingsIfDirty(self.assetPath);
+ AssetDatabase.ImportAsset(self.assetPath, ImportAssetOptions.ForceUpdate);
+ }
+
+ static void ExtractMaterialsAndTextures(ScriptedImporter self)
+ {
+ if (string.IsNullOrEmpty(self.assetPath))
+ {
+ return;
+ }
+
+ Action addRemap = externalObject =>
+ {
+ self.AddRemap(new AssetImporter.SourceAssetIdentifier(typeof(UnityEngine.Texture2D), externalObject.name), externalObject);
+ };
+ Action> onCompleted = _ =>
+ {
+ AssetDatabase.ImportAsset(self.assetPath, ImportAssetOptions.ForceUpdate);
+ self.ExtractMaterials();
+ AssetDatabase.ImportAsset(self.assetPath, ImportAssetOptions.ForceUpdate);
+ };
+
+ TextureExtractor.ExtractTextures(self.assetPath,
+ self.GetSubAssets(self.assetPath).ToArray(),
+ addRemap,
+ onCompleted
+ );
+ }
+
+ public static void ExtractMaterials(this ScriptedImporter importer)
+ {
+ if (string.IsNullOrEmpty(importer.assetPath))
+ {
+ return;
+ }
+ var path = $"{Path.GetDirectoryName(importer.assetPath)}/{Path.GetFileNameWithoutExtension(importer.assetPath)}.Materials";
+ var info = TextureExtractor.SafeCreateDirectory(path);
+
+ foreach (var asset in importer.GetSubAssets(importer.assetPath))
+ {
+ ExtractSubAsset(asset, $"{path}/{asset.name}.mat", false);
+ }
+ }
+
+ private static void ExtractSubAsset(UnityEngine.Object subAsset, string destinationPath, bool isForceUpdate)
+ {
+ string assetPath = AssetDatabase.GetAssetPath(subAsset);
+
+ var clone = UnityEngine.Object.Instantiate(subAsset);
+ AssetDatabase.CreateAsset(clone, destinationPath);
+
+ var assetImporter = AssetImporter.GetAtPath(assetPath);
+ assetImporter.AddRemap(new AssetImporter.SourceAssetIdentifier(clone), clone);
+
+ if (isForceUpdate)
+ {
+ AssetDatabase.WriteImportSettingsIfDirty(assetPath);
+ AssetDatabase.ImportAsset(assetPath, ImportAssetOptions.ForceUpdate);
+ }
+ }
+ }
+}
diff --git a/Assets/UniGLTF/Editor/UniGLTF/ImporterMenu.cs.meta b/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/EditorMaterial.cs.meta
similarity index 71%
rename from Assets/UniGLTF/Editor/UniGLTF/ImporterMenu.cs.meta
rename to Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/EditorMaterial.cs.meta
index 47d70b596..ae9423568 100644
--- a/Assets/UniGLTF/Editor/UniGLTF/ImporterMenu.cs.meta
+++ b/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/EditorMaterial.cs.meta
@@ -1,7 +1,5 @@
fileFormatVersion: 2
-guid: ae2833922b06981439883d1e924b4cd0
-timeCreated: 1517153624
-licenseType: Free
+guid: d87d4a592573eb048916575e202af37f
MonoImporter:
externalObjects: {}
serializedVersion: 2
diff --git a/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/GlbScriptedImporter.cs b/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/GlbScriptedImporter.cs
new file mode 100644
index 000000000..ae92a0387
--- /dev/null
+++ b/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/GlbScriptedImporter.cs
@@ -0,0 +1,25 @@
+using UnityEditor.Experimental.AssetImporters;
+using UnityEngine;
+
+
+namespace UniGLTF
+{
+ [ScriptedImporter(1, "glb")]
+ public class GlbScriptedImporter : ScriptedImporter
+ {
+ [SerializeField]
+ Axises m_reverseAxis = default;
+
+ public override void OnImportAsset(AssetImportContext ctx)
+ {
+ try
+ {
+ ScriptedImporterImpl.Import(this, ctx, m_reverseAxis);
+ }
+ catch (System.Exception ex)
+ {
+ Debug.LogError(ex);
+ }
+ }
+ }
+}
diff --git a/Assets/UniGLTF/Editor/UniGLTF/gltfAssetPostprocessor.cs.meta b/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/GlbScriptedImporter.cs.meta
similarity index 69%
rename from Assets/UniGLTF/Editor/UniGLTF/gltfAssetPostprocessor.cs.meta
rename to Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/GlbScriptedImporter.cs.meta
index bf1323947..7866ddd3f 100644
--- a/Assets/UniGLTF/Editor/UniGLTF/gltfAssetPostprocessor.cs.meta
+++ b/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/GlbScriptedImporter.cs.meta
@@ -1,8 +1,7 @@
fileFormatVersion: 2
-guid: 7bbb264b34e75dd438622e1f29f0f46c
-timeCreated: 1517119659
-licenseType: Free
+guid: cc45016b844e7624dae3aec10fb443ea
MonoImporter:
+ externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
diff --git a/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/GlbScriptedImporterEditorGUI.cs b/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/GlbScriptedImporterEditorGUI.cs
new file mode 100644
index 000000000..fb1b4634b
--- /dev/null
+++ b/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/GlbScriptedImporterEditorGUI.cs
@@ -0,0 +1,49 @@
+using UnityEditor;
+using UnityEditor.Experimental.AssetImporters;
+using UnityEngine;
+
+namespace UniGLTF
+{
+ [CustomEditor(typeof(GlbScriptedImporter))]
+ public class GlbScriptedImporterEditorGUI : ScriptedImporterEditor
+ {
+ GlbScriptedImporter m_importer;
+ GltfParser m_parser;
+
+ public override void OnEnable()
+ {
+ m_importer = target as GlbScriptedImporter;
+ m_parser = new GltfParser();
+ m_parser.ParsePath(m_importer.assetPath);
+ }
+
+ enum Tabs
+ {
+ Model,
+ Animation,
+ Materials,
+ }
+ static Tabs s_currentTab;
+
+ public override void OnInspectorGUI()
+ {
+ s_currentTab = MeshUtility.TabBar.OnGUI(s_currentTab);
+ GUILayout.Space(10);
+
+ switch (s_currentTab)
+ {
+ case Tabs.Model:
+ base.OnInspectorGUI();
+ break;
+
+ case Tabs.Animation:
+ EditorAnimation.OnGUIAnimation(m_parser);
+ break;
+
+ case Tabs.Materials:
+ EditorMaterial.OnGUIMaterial(m_importer, m_parser);
+ break;
+ }
+ }
+ }
+}
diff --git a/Assets/UniGLTF/Runtime/UniJSON/ActionDisposer.cs.meta b/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/GlbScriptedImporterEditorGUI.cs.meta
similarity index 69%
rename from Assets/UniGLTF/Runtime/UniJSON/ActionDisposer.cs.meta
rename to Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/GlbScriptedImporterEditorGUI.cs.meta
index 1a21d6618..f20742643 100644
--- a/Assets/UniGLTF/Runtime/UniJSON/ActionDisposer.cs.meta
+++ b/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/GlbScriptedImporterEditorGUI.cs.meta
@@ -1,8 +1,7 @@
fileFormatVersion: 2
-guid: ff15446e31b14ac409251c931b7c2038
-timeCreated: 1531893103
-licenseType: Free
+guid: 706590752e82d004e99da97aff535f67
MonoImporter:
+ externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
diff --git a/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/GltfScriptedImporter.cs b/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/GltfScriptedImporter.cs
index 5e1a9d151..fe4fc605b 100644
--- a/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/GltfScriptedImporter.cs
+++ b/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/GltfScriptedImporter.cs
@@ -1,102 +1,25 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using UnityEditor;
using UnityEditor.Experimental.AssetImporters;
using UnityEngine;
namespace UniGLTF
{
- [ScriptedImporter(1, "glb")]
+ [ScriptedImporter(1, "gltf")]
public class GltfScriptedImporter : ScriptedImporter
{
[SerializeField]
Axises m_reverseAxis = default;
- const string TextureDirName = "Textures";
- const string MaterialDirName = "Materials";
-
public override void OnImportAsset(AssetImportContext ctx)
{
- Debug.Log("OnImportAsset to " + ctx.assetPath);
-
try
{
- // Parse
- var parser = new GltfParser();
- parser.ParsePath(ctx.assetPath);
-
- // Build Unity Model
- var externalObjectMap = GetExternalObjectMap()
- .Select(kv => (kv.Key.name, kv.Value))
- ;
-
- var context = new ImporterContext(parser, null, externalObjectMap);
- context.InvertAxis = m_reverseAxis;
- context.Load();
- context.ShowMeshes();
-
- // Texture
- foreach (var info in context.TextureFactory.Textures)
- {
- if (!info.IsUsed)
- {
- continue;
- }
- if (!info.IsExternal)
- {
- var texture = info.Texture;
- ctx.AddObjectToAsset(texture.name, texture);
- }
- }
-
- // Material
- foreach (var info in context.MaterialFactory.Materials)
- {
- if (!info.UseExternal)
- {
- var material = info.Asset;
- ctx.AddObjectToAsset(material.name, material);
- }
- }
-
- // Mesh
- foreach (var mesh in context.Meshes.Select(x => x.Mesh))
- {
- ctx.AddObjectToAsset(mesh.name, mesh);
- }
-
- // Animation
- foreach (var clip in context.AnimationClips)
- {
- ctx.AddObjectToAsset(clip.name, clip);
- }
-
- // Root
- ctx.AddObjectToAsset(context.Root.name, context.Root);
- ctx.SetMainObject(context.Root);
+ ScriptedImporterImpl.Import(this, ctx, m_reverseAxis);
}
catch (System.Exception ex)
{
Debug.LogError(ex);
}
}
-
- public void ExtractMaterialsAndTextures()
- {
- this.ExtractTextures(TextureDirName, () =>
- {
- this.ExtractAssets(MaterialDirName, ".mat");
- AssetDatabase.ImportAsset(assetPath, ImportAssetOptions.ForceUpdate);
- });
- }
-
- public void SetExternalUnityObject(UnityEditor.AssetImporter.SourceAssetIdentifier sourceAssetIdentifier, T obj) where T : UnityEngine.Object
- {
- this.AddRemap(sourceAssetIdentifier, obj);
- AssetDatabase.WriteImportSettingsIfDirty(this.assetPath);
- AssetDatabase.ImportAsset(this.assetPath, ImportAssetOptions.ForceUpdate);
- }
}
}
diff --git a/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/GltfScriptedImporterEditorGUI.cs b/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/GltfScriptedImporterEditorGUI.cs
index 579ba7c36..b1c4723d5 100644
--- a/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/GltfScriptedImporterEditorGUI.cs
+++ b/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/GltfScriptedImporterEditorGUI.cs
@@ -1,6 +1,3 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
using UnityEditor;
using UnityEditor.Experimental.AssetImporters;
using UnityEngine;
@@ -40,98 +37,13 @@ namespace UniGLTF
break;
case Tabs.Animation:
- OnGUIAnimation(m_importer, m_parser);
+ EditorAnimation.OnGUIAnimation(m_parser);
break;
case Tabs.Materials:
- OnGUIMaterial(m_importer, m_parser);
+ EditorMaterial.OnGUIMaterial(m_importer, m_parser);
break;
}
}
-
- static bool s_foldMaterials;
- static bool s_foldTextures;
-
- class TmpGuiEnable : IDisposable
- {
- bool m_backup;
- public TmpGuiEnable(bool enable)
- {
- m_backup = GUI.enabled;
- GUI.enabled = enable;
- }
-
- public void Dispose()
- {
- GUI.enabled = m_backup;
- }
- }
-
- static void OnGUIMaterial(GltfScriptedImporter importer, GltfParser parser)
- {
- var canExtract = !importer.GetExternalObjectMap().Any(x => x.Value is Material || x.Value is Texture2D);
- using (new TmpGuiEnable(canExtract))
- {
- if (GUILayout.Button("Extract Materials And Textures ..."))
- {
- importer.ExtractMaterialsAndTextures();
- }
- }
-
- // ObjectMap
- s_foldMaterials = EditorGUILayout.Foldout(s_foldMaterials, "Remapped Materials");
- if (s_foldMaterials)
- {
- DrawRemapGUI(importer, parser.GLTF.materials.Select(x => x.name));
- }
-
- s_foldTextures = EditorGUILayout.Foldout(s_foldTextures, "Remapped Textures");
- if (s_foldTextures)
- {
- DrawRemapGUI(importer, parser.EnumerateTextures().Select(x => x.Name));
- }
-
- if (GUILayout.Button("Clear"))
- {
- importer.ClearExternalObjects();
- importer.ClearExternalObjects();
- }
- }
-
- static void DrawRemapGUI(GltfScriptedImporter importer, IEnumerable names) where T : UnityEngine.Object
- {
- EditorGUI.indentLevel++;
- var map = importer.GetExternalObjectMap()
- .Select(x => (x.Key.name, x.Value as T))
- .Where(x => x.Item2 != null)
- .ToDictionary(x => x.Item1, x => x.Item2)
- ;
- foreach (var name in names)
- {
- if (string.IsNullOrEmpty(name))
- {
- throw new System.ArgumentNullException();
- }
-
- EditorGUILayout.BeginHorizontal();
- EditorGUILayout.PrefixLabel(name);
- map.TryGetValue(name, out T value);
- var asset = EditorGUILayout.ObjectField(value, typeof(T), true) as T;
- if (asset != value)
- {
- importer.SetExternalUnityObject(new AssetImporter.SourceAssetIdentifier(value), asset);
- }
- EditorGUILayout.EndHorizontal();
- }
- EditorGUI.indentLevel--;
- }
-
- static void OnGUIAnimation(GltfScriptedImporter importer, GltfParser parser)
- {
- foreach (var a in parser.GLTF.animations)
- {
- GUILayout.Label(a.name);
- }
- }
}
}
diff --git a/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/GltfScriptedImporterEditorGUI.cs.meta b/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/GltfScriptedImporterEditorGUI.cs.meta
index f20742643..20e7e95c7 100644
--- a/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/GltfScriptedImporterEditorGUI.cs.meta
+++ b/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/GltfScriptedImporterEditorGUI.cs.meta
@@ -1,5 +1,5 @@
fileFormatVersion: 2
-guid: 706590752e82d004e99da97aff535f67
+guid: 16c69c858a1da5e4088d72a546a2963e
MonoImporter:
externalObjects: {}
serializedVersion: 2
diff --git a/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/ScriptedImporterExtension.cs b/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/ScriptedImporterExtension.cs
index c60524427..41f91f6df 100644
--- a/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/ScriptedImporterExtension.cs
+++ b/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/ScriptedImporterExtension.cs
@@ -3,9 +3,6 @@ using System.IO;
using System.Linq;
using UnityEditor.Experimental.AssetImporters;
using UnityEditor;
-using System;
-using UnityEngine;
-using System.Text.RegularExpressions;
namespace UniGLTF
{
@@ -13,32 +10,15 @@ namespace UniGLTF
{
public static void ClearExternalObjects(this ScriptedImporter importer) where T : UnityEngine.Object
{
- foreach (var extarnalObject in importer.GetExternalObjectMap().Where(x => x.Key.type == typeof(T)))
+ foreach (var externalObject in importer.GetExternalObjectMap().Where(x => x.Key.type == typeof(T)))
{
- importer.RemoveRemap(extarnalObject.Key);
+ importer.RemoveRemap(externalObject.Key);
}
AssetDatabase.WriteImportSettingsIfDirty(importer.assetPath);
AssetDatabase.ImportAsset(importer.assetPath, ImportAssetOptions.ForceUpdate);
}
- public static void ClearExtarnalObjects(this ScriptedImporter importer)
- {
- foreach (var extarnalObject in importer.GetExternalObjectMap())
- {
- importer.RemoveRemap(extarnalObject.Key);
- }
-
- AssetDatabase.WriteImportSettingsIfDirty(importer.assetPath);
- AssetDatabase.ImportAsset(importer.assetPath, ImportAssetOptions.ForceUpdate);
- }
-
- private static T GetSubAsset(this ScriptedImporter importer, string assetPath) where T : UnityEngine.Object
- {
- return importer.GetSubAssets(assetPath)
- .FirstOrDefault();
- }
-
public static IEnumerable GetSubAssets(this ScriptedImporter importer, string assetPath) where T : UnityEngine.Object
{
return AssetDatabase
@@ -47,177 +27,5 @@ namespace UniGLTF
.Where(x => x is T)
.Select(x => x as T);
}
-
- private static void ExtractFromAsset(UnityEngine.Object subAsset, string destinationPath, bool isForceUpdate)
- {
- string assetPath = AssetDatabase.GetAssetPath(subAsset);
-
- var clone = UnityEngine.Object.Instantiate(subAsset);
- AssetDatabase.CreateAsset(clone, destinationPath);
-
- var assetImporter = AssetImporter.GetAtPath(assetPath);
- assetImporter.AddRemap(new AssetImporter.SourceAssetIdentifier(subAsset), clone);
-
- if (isForceUpdate)
- {
- AssetDatabase.WriteImportSettingsIfDirty(assetPath);
- AssetDatabase.ImportAsset(assetPath, ImportAssetOptions.ForceUpdate);
- }
- }
-
- public static void ExtractAssets(this ScriptedImporter importer, string dirName, string extension) where T : UnityEngine.Object
- {
- if (string.IsNullOrEmpty(importer.assetPath))
- return;
-
- var subAssets = importer.GetSubAssets(importer.assetPath);
-
- var path = string.Format("{0}/{1}.{2}",
- Path.GetDirectoryName(importer.assetPath),
- Path.GetFileNameWithoutExtension(importer.assetPath),
- dirName
- );
-
- var info = importer.SafeCreateDirectory(path);
-
- foreach (var asset in subAssets)
- {
- ExtractFromAsset(asset, string.Format("{0}/{1}{2}", path, asset.name, extension), false);
- }
- }
-
- class TextureExtractor
- {
- GltfParser m_parser;
- public GltfParser Parser => m_parser;
-
- public glTF GLTF => m_parser.GLTF;
- public IStorage Storage => m_parser.Storage;
-
- public readonly Dictionary Textures = new Dictionary();
- UnityEngine.Texture2D[] m_subAssets;
- string m_path;
-
- public TextureExtractor(ScriptedImporter importer)
- {
- // parse GLTF
- m_parser = new GltfParser();
- m_parser.ParsePath(importer.assetPath);
-
- m_path = $"{Path.GetDirectoryName(importer.assetPath)}/{Path.GetFileNameWithoutExtension(importer.assetPath)}.Textures";
- m_subAssets = importer.GetSubAssets(importer.assetPath).ToArray();
- }
-
- static Regex s_mimeTypeReg = new Regex("image/(?.*)$");
-
- public void Extract(GetTextureParam param)
- {
- var subAsset = m_subAssets.FirstOrDefault(x => x.name == param.Name);
- string targetPath = "";
-
- switch (param.TextureType)
- {
- case GetTextureParam.METALLIC_GLOSS_PROP:
- case GetTextureParam.OCCLUSION_PROP:
- {
- // write converted texture
- targetPath = string.Format("{0}/{1}{2}",
- m_path,
- param.Name,
- ".png"
- );
- File.WriteAllBytes(targetPath, subAsset.EncodeToPNG().ToArray());
- break;
- }
-
- default:
- {
- // write original bytes
- targetPath = string.Format("{0}/{1}{2}",
- m_path,
- param.Name,
- ".png"
- );
- var gltfTexture = GLTF.textures[param.Index0.Value];
- File.WriteAllBytes(targetPath, GLTF.GetImageBytes(Storage, gltfTexture.source).ToArray());
- break;
- }
- }
- AssetDatabase.ImportAsset(targetPath);
- Textures.Add(targetPath, param);
- }
- }
-
- public static void ExtractTextures(this ScriptedImporter importer, string dirName, Action onCompleted = null)
- {
- if (string.IsNullOrEmpty(importer.assetPath))
- {
- return;
- }
-
- var path = string.Format("{0}/{1}.{2}",
- Path.GetDirectoryName(importer.assetPath),
- Path.GetFileNameWithoutExtension(importer.assetPath),
- dirName
- );
- importer.SafeCreateDirectory(path);
-
- // Reload Model
- var extractor = new TextureExtractor(importer);
-
- foreach (var material in extractor.GLTF.materials)
- {
- foreach (var x in extractor.Parser.EnumerateTextures(material))
- {
- extractor.Extract(x);
- }
- }
-
- EditorApplication.delayCall += () =>
- {
- foreach (var kv in extractor.Textures)
- {
- var targetPath = kv.Key;
- var param = kv.Value;
-
- // TextureImporter
- var targetTextureImporter = AssetImporter.GetAtPath(targetPath) as TextureImporter;
-
- switch (param.TextureType)
- {
- case GetTextureParam.OCCLUSION_PROP:
- case GetTextureParam.METALLIC_GLOSS_PROP:
- targetTextureImporter.sRGBTexture = false;
- break;
-
- case GetTextureParam.NORMAL_PROP:
- targetTextureImporter.textureType = TextureImporterType.NormalMap;
- break;
- }
-
- targetTextureImporter.SaveAndReimport();
-
- // remap
- var externalObject = AssetDatabase.LoadAssetAtPath(targetPath);
- importer.AddRemap(new AssetImporter.SourceAssetIdentifier(typeof(UnityEngine.Texture2D), externalObject.name), externalObject);
- }
-
- AssetDatabase.ImportAsset(importer.assetPath, ImportAssetOptions.ForceUpdate);
-
- if (onCompleted != null)
- {
- onCompleted();
- }
- };
- }
-
- public static DirectoryInfo SafeCreateDirectory(this ScriptedImporter importer, string path)
- {
- if (Directory.Exists(path))
- {
- return null;
- }
- return Directory.CreateDirectory(path);
- }
}
}
diff --git a/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/ScriptedImporterImpl.cs b/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/ScriptedImporterImpl.cs
new file mode 100644
index 000000000..0a93dff14
--- /dev/null
+++ b/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/ScriptedImporterImpl.cs
@@ -0,0 +1,95 @@
+using System.Collections.Generic;
+using System.Linq;
+using UnityEditor;
+using UnityEditor.Experimental.AssetImporters;
+using UnityEngine;
+
+namespace UniGLTF
+{
+ public static class ScriptedImporterImpl
+ {
+ ///
+ /// glb をパースして、UnityObject化、さらにAsset化する
+ ///
+ ///
+ ///
+ ///
+ public static void Import(ScriptedImporter scriptedImporter, AssetImportContext context, Axises reverseAxis)
+ {
+#if VRM_DEVELOP
+ Debug.Log("OnImportAsset to " + scriptedImporter.assetPath);
+#endif
+
+ //
+ // Parse(parse glb, parser gltf json)
+ //
+ var parser = new GltfParser();
+ parser.ParsePath(scriptedImporter.assetPath);
+
+ //
+ // Import(create unity objects)
+ //
+ var externalObjectMap = scriptedImporter.GetExternalObjectMap();
+
+ using (var loaded = new ImporterContext(parser, null,
+ externalObjectMap.Where(x => x.Value != null).Select(x => (x.Value.name, x.Value)).Concat(
+ EnumerateTexturesFromUri(externalObjectMap, parser, UnityPath.FromUnityPath(scriptedImporter.assetPath).Parent))))
+ {
+ loaded.InvertAxis = reverseAxis;
+ loaded.Load();
+ loaded.ShowMeshes();
+
+ loaded.TransferOwnership(o =>
+ {
+#if VRM_DEVELOP
+ Debug.Log($"[{o.GetType().Name}] {o.name} will not destroy");
+#endif
+
+ context.AddObjectToAsset(o.name, o);
+ if (o is GameObject)
+ {
+ // Root GameObject is main object
+ context.SetMainObject(loaded.Root);
+ }
+
+ return true;
+ });
+ }
+ }
+
+ public static IEnumerable<(string, UnityEngine.Object)> EnumerateTexturesFromUri(Dictionary exclude,
+ GltfParser parser, UnityPath dir)
+ {
+ foreach (var texParam in parser.EnumerateTextures())
+ {
+ switch (texParam.TextureType)
+ {
+ case GetTextureParam.METALLIC_GLOSS_PROP:
+ case GetTextureParam.OCCLUSION_PROP:
+ break;
+
+ default:
+ {
+ var gltfTexture = parser.GLTF.textures.First(y => y.name == texParam.GltflName);
+ var gltfImage = parser.GLTF.images[gltfTexture.source];
+ if (!string.IsNullOrEmpty(gltfImage.uri))
+ {
+ var child = dir.Child(gltfImage.uri);
+ var asset = AssetDatabase.LoadAssetAtPath(child.Value);
+ if (asset == null)
+ {
+ throw new System.IO.FileNotFoundException($"{child}");
+ }
+ // Debug.Log($"exists: {child}: {asset}");
+ if (exclude == null || !exclude.Any(kv => kv.Value.name == asset.name))
+ {
+ yield return (asset.name, asset);
+ }
+ }
+ }
+ break;
+ }
+ }
+ }
+ }
+}
diff --git a/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/ScriptedImporterImpl.cs.meta b/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/ScriptedImporterImpl.cs.meta
new file mode 100644
index 000000000..0581f26f1
--- /dev/null
+++ b/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/ScriptedImporterImpl.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 85bf14b48ed135743828ee49a830b1c6
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/TextureExtractor.cs b/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/TextureExtractor.cs
new file mode 100644
index 000000000..64db7ab81
--- /dev/null
+++ b/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/TextureExtractor.cs
@@ -0,0 +1,184 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using UnityEngine;
+using UnityEditor;
+using System.Linq;
+
+namespace UniGLTF
+{
+ public class TextureExtractor
+ {
+ const string TextureDirName = "Textures";
+
+ GltfParser m_parser;
+ public GltfParser Parser => m_parser;
+
+ public glTF GLTF => m_parser.GLTF;
+ public IStorage Storage => m_parser.Storage;
+
+ public readonly Dictionary Textures = new Dictionary();
+ UnityEngine.Texture2D[] m_subAssets;
+ string m_path;
+
+ public TextureExtractor(string assetPath, UnityEngine.Texture2D[] subAssets)
+ {
+ // parse GLTF
+ m_parser = new GltfParser();
+ m_parser.ParsePath(assetPath);
+
+ m_path = $"{Path.GetDirectoryName(assetPath)}/{Path.GetFileNameWithoutExtension(assetPath)}.Textures";
+ SafeCreateDirectory(m_path);
+
+ if (assetPath == null)
+ {
+ throw new ArgumentNullException();
+ }
+ m_subAssets = subAssets;
+ }
+
+ public static string GetExt(string mime, string uri)
+ {
+ switch (mime)
+ {
+ case "image/png": return ".png";
+ case "image/jpeg": return ".jpg";
+ }
+
+ return Path.GetExtension(uri).ToLower();
+ }
+
+ public void Extract(GetTextureParam param, bool hasUri)
+ {
+ if (Textures.Values.Contains(param))
+ {
+ return;
+ }
+
+ var subAsset = m_subAssets.FirstOrDefault(x => x.name == param.ConvertedName);
+ string targetPath = "";
+
+ if (hasUri && !param.ExtractConverted)
+ {
+ var gltfTexture = GLTF.textures[param.Index0.Value];
+ var gltfImage = GLTF.images[gltfTexture.source];
+ var ext = GetExt(gltfImage.mimeType, gltfImage.uri);
+ targetPath = $"{Path.GetDirectoryName(m_path)}/{param.GltflName}{ext}";
+ }
+ else
+ {
+
+ switch (param.TextureType)
+ {
+ case GetTextureParam.METALLIC_GLOSS_PROP:
+ case GetTextureParam.OCCLUSION_PROP:
+ {
+ // write converted texture
+ targetPath = $"{m_path}/{param.ConvertedName}.png";
+ File.WriteAllBytes(targetPath, subAsset.EncodeToPNG().ToArray());
+ AssetDatabase.ImportAsset(targetPath);
+ break;
+ }
+
+ default:
+ {
+ // write original bytes
+ var gltfTexture = GLTF.textures[param.Index0.Value];
+ var gltfImage = GLTF.images[gltfTexture.source];
+ var ext = GetExt(gltfImage.mimeType, gltfImage.uri);
+ targetPath = $"{m_path}/{param.GltflName}{ext}";
+ File.WriteAllBytes(targetPath, GLTF.GetImageBytes(Storage, gltfTexture.source).ToArray());
+ AssetDatabase.ImportAsset(targetPath);
+ break;
+ }
+ }
+ }
+
+ Textures.Add(targetPath, param);
+ }
+
+ public static DirectoryInfo SafeCreateDirectory(string path)
+ {
+ if (Directory.Exists(path))
+ {
+ return null;
+ }
+ return Directory.CreateDirectory(path);
+ }
+
+ ///
+ ///
+ /// * Texture(.png etc...)をディスクに書き出す
+ /// * EditorApplication.delayCall で処理を進めて 書き出した画像が Asset として成立するのを待つ
+ /// * 書き出した Asset から TextureImporter を取得して設定する
+ ///
+ ///
+ ///
+ ///
+ ///
+ public static void ExtractTextures(string assetPath, Texture2D[] subAssets, Action addRemap, Action> onCompleted = null)
+ {
+ var extractor = new TextureExtractor(assetPath, subAssets);
+ var normalMaps = new List();
+ foreach (var material in extractor.GLTF.materials)
+ {
+ foreach (var x in extractor.Parser.EnumerateTextures(material))
+ {
+ var gltfTexture = extractor.GLTF.textures[x.Index0.Value];
+ var gltfImage = extractor.GLTF.images[gltfTexture.source];
+ extractor.Extract(x, !string.IsNullOrEmpty(gltfImage.uri));
+ }
+ }
+
+ EditorApplication.delayCall += () =>
+ {
+ foreach (var kv in extractor.Textures)
+ {
+ var targetPath = kv.Key;
+ var param = kv.Value;
+
+ // TextureImporter
+ var targetTextureImporter = AssetImporter.GetAtPath(targetPath) as TextureImporter;
+ if (targetTextureImporter != null)
+ {
+ switch (param.TextureType)
+ {
+ case GetTextureParam.OCCLUSION_PROP:
+ case GetTextureParam.METALLIC_GLOSS_PROP:
+#if VRM_DEVELOP
+ Debug.Log($"{targetPath} => linear");
+#endif
+ targetTextureImporter.sRGBTexture = false;
+ targetTextureImporter.SaveAndReimport();
+ break;
+
+ case GetTextureParam.NORMAL_PROP:
+#if VRM_DEVELOP
+ Debug.Log($"{targetPath} => normalmap");
+#endif
+ targetTextureImporter.textureType = TextureImporterType.NormalMap;
+ targetTextureImporter.SaveAndReimport();
+ break;
+ }
+ }
+ else
+ {
+ throw new FileNotFoundException(targetPath);
+ }
+
+ // remap
+ var externalObject = AssetDatabase.LoadAssetAtPath(targetPath);
+ if (externalObject != null)
+ {
+ addRemap(externalObject);
+ }
+ }
+
+ if (onCompleted != null)
+ {
+ onCompleted(extractor.Textures.Keys);
+ }
+ };
+ }
+ }
+}
diff --git a/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/TextureExtractor.cs.meta b/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/TextureExtractor.cs.meta
new file mode 100644
index 000000000..503d37228
--- /dev/null
+++ b/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/TextureExtractor.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 556e0ca7f0824e44b9000d04e0e9914c
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Assets/UniGLTF/Editor/UniGLTF/gltfAssetPostprocessor.cs b/Assets/UniGLTF/Editor/UniGLTF/gltfAssetPostprocessor.cs
deleted file mode 100644
index e12c8b02c..000000000
--- a/Assets/UniGLTF/Editor/UniGLTF/gltfAssetPostprocessor.cs
+++ /dev/null
@@ -1,89 +0,0 @@
-#if false
-using System;
-using System.IO;
-using UnityEditor;
-using UnityEngine;
-
-
-namespace UniGLTF
-{
- public class gltfAssetPostprocessor : AssetPostprocessor
- {
- 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 ImportAsset(string src, string ext, UnityPath prefabPath)
- {
- if (!prefabPath.IsUnderAssetsFolder)
- {
- Debug.LogWarningFormat("out of asset path: {0}", prefabPath);
- return;
- }
-
- var parser = new GltfParser();
- parser.ParsePath(src);
- var context = new ImporterContext(parser);
-
- // Extract textures to assets folder
- context.ExtractImages(prefabPath);
-
- ImportDelayed(src, prefabPath, context);
- }
-
- 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();
- }
- };
- }
- }
-}
-#endif
\ No newline at end of file
diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/GltfParser.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/GltfParser.cs
index 63d352b11..92b5445cf 100644
--- a/Assets/UniGLTF/Runtime/UniGLTF/IO/GltfParser.cs
+++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/GltfParser.cs
@@ -229,13 +229,20 @@ namespace UniGLTF
for (int i = 0; i < GLTF.textures.Count; ++i)
{
var gltfTexture = GLTF.textures[i];
- if (string.IsNullOrEmpty(gltfTexture.name))
+ var gltfImage = GLTF.images[gltfTexture.source];
+ if (!string.IsNullOrEmpty(gltfImage.uri))
{
- // use image name
- gltfTexture.name = GLTF.images[gltfTexture.source].name;
+ // from image uri
+ gltfTexture.name = Path.GetFileNameWithoutExtension(gltfImage.uri);
}
if (string.IsNullOrEmpty(gltfTexture.name))
{
+ // use image name
+ gltfTexture.name = gltfImage.name;
+ }
+ if (string.IsNullOrEmpty(gltfTexture.name))
+ {
+ // no name
var newName = $"texture_{i}";
if (!used.Add(newName))
{
@@ -250,15 +257,17 @@ namespace UniGLTF
else
{
var lower = gltfTexture.name.ToLower();
- if (used.Contains(lower))
+ if (!used.Add(lower))
{
// rename
var uname = lower + "_" + Guid.NewGuid().ToString("N");
Debug.LogWarning($"same name: {lower} => {uname}");
gltfTexture.name = uname;
- lower = uname;
+ if (!used.Add(uname))
+ {
+ throw new Exception();
+ }
}
- used.Add(lower);
}
}
}
@@ -325,62 +334,6 @@ namespace UniGLTF
}
}
- public string GetTextureExtension(int imageIndex)
- {
- foreach (var m in GLTF.materials)
- {
- if (m.pbrMetallicRoughness != null)
- {
- // base color
- if (m.pbrMetallicRoughness?.baseColorTexture != null)
- {
- if (m.pbrMetallicRoughness.baseColorTexture.index == imageIndex)
- {
- return "";
- }
- }
-
- // metallic roughness
- if (m.pbrMetallicRoughness?.metallicRoughnessTexture != null)
- {
- if (m.pbrMetallicRoughness.metallicRoughnessTexture.index == imageIndex)
- {
- return ".metallicRoughness";
- }
- }
- }
-
- // emission
- if (m.emissiveTexture != null)
- {
- if (m.emissiveTexture.index == imageIndex)
- {
- return "";
- }
- }
-
- // normal
- if (m.normalTexture != null)
- {
- if (m.normalTexture.index == imageIndex)
- {
- return "";
- }
- }
-
- // occlusion
- if (m.occlusionTexture != null)
- {
- if (m.occlusionTexture.index == imageIndex)
- {
- return ".occlusion";
- }
- }
- }
-
- return "";
- }
-
public IEnumerable EnumerateTextures(glTFMaterial m)
{
if (m.pbrMetallicRoughness != null)
@@ -425,7 +378,7 @@ namespace UniGLTF
var m = GLTF.materials[i];
foreach (var x in EnumerateTextures(m))
{
- if (used.Add(x.Name))
+ if (used.Add(x.ConvertedName))
{
yield return x;
}
diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/ImporterContext.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/ImporterContext.cs
index 305a74182..991ce537c 100644
--- a/Assets/UniGLTF/Runtime/UniGLTF/IO/ImporterContext.cs
+++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/ImporterContext.cs
@@ -103,17 +103,6 @@ namespace UniGLTF
throw new UniGLTFNotSupportedException("draco is not supported");
}
- // using (MeasureTime("LoadTextures"))
- // {
- // for (int i = 0; i < GLTF.materials.Count; ++i)
- // {
- // foreach (var param in MaterialFactory.EnumerateGetTextureparam(i))
- // {
- // await m_textureFactory.GetTextureAsync(GLTF, param);
- // }
- // }
- // }
-
using (MeasureTime("LoadMaterials"))
{
await m_materialFactory.LoadMaterialsAsync(m_awaitCaller, m_textureFactory.GetTextureAsync);
@@ -201,8 +190,9 @@ namespace UniGLTF
}
#endregion
- #region Imported
+ #region Imported
public GameObject Root;
+ bool m_ownRoot = true;
public List Nodes = new List();
public List Meshes = new List();
@@ -216,6 +206,14 @@ namespace UniGLTF
}
}
}
+ void RemoveMesh(Mesh mesh)
+ {
+ var index = Meshes.FindIndex(x => x.Mesh == mesh);
+ if (index >= 0)
+ {
+ Meshes.RemoveAt(index);
+ }
+ }
public void EnableUpdateWhenOffscreen()
{
@@ -236,20 +234,39 @@ namespace UniGLTF
#endregion
///
- /// Importに使った一時オブジェクトを破棄する
- ///
- /// 変換のあるテクスチャで、変換前のもの
- /// normal, occlusion, metallicRoughness
+ /// ImporterContextが所有する UnityEngine.Object を破棄する
///
public virtual void Dispose()
{
- foreach (var x in m_textureFactory.Textures)
+ Action destroy = UnityResourceDestroyer.DestroyResource();
+
+ foreach (var x in AnimationClips)
{
- if (!x.IsUsed)
- {
- // Destroy temporary texture object
- UnityEngine.Object.Destroy(x.Texture);
- }
+#if VRM_DEVELOP
+ Debug.Log($"Destroy {x}");
+#endif
+ destroy(x);
+ }
+ AnimationClips.Clear();
+
+ foreach (var x in Meshes)
+ {
+#if VRM_DEVELOP
+ Debug.Log($"Destroy {x}");
+#endif
+ destroy(x.Mesh);
+ }
+ Meshes.Clear();
+
+ m_materialFactory.Dispose();
+ m_textureFactory.Dispose();
+
+ if (m_ownRoot && Root != null)
+ {
+#if VRM_DEVELOP
+ Debug.Log($"Destroy {Root}");
+#endif
+ destroy(Root);
}
}
@@ -257,33 +274,64 @@ namespace UniGLTF
/// Root ヒエラルキーで使っているリソース
///
///
- public virtual IEnumerable ModelOwnResources()
+ public virtual void TransferOwnership(TakeOwnershipFunc take)
{
+ var list = new List();
foreach (var mesh in Meshes)
{
- yield return mesh.Mesh;
+ if (take(mesh.Mesh))
+ {
+ list.Add(mesh.Mesh);
+ }
}
- foreach (var material in m_materialFactory.Materials)
+ foreach (var x in list)
{
- yield return material.Asset;
- }
- foreach (var texture in m_textureFactory.Textures)
- {
- yield return texture.Texture;
+ RemoveMesh(x as Mesh);
}
+
+ TextureFactory.TransferOwnership(take);
+ MaterialFactory.TransferOwnership(take);
+
+ list.Clear();
foreach (var animation in AnimationClips)
{
- yield return animation;
+ if (take(animation))
+ {
+ list.Add(animation);
+ }
+ }
+ foreach (var x in list)
+ {
+ AnimationClips.Remove(x as AnimationClip);
+ }
+
+ if (m_ownRoot && Root != null)
+ {
+ if (take(Root))
+ {
+ // 所有権(Dispose権)
+ m_ownRoot = false;
+ }
}
}
+ ///
+ /// RootにUnityResourceDestroyerをアタッチして、
+ /// RootをUnityEngine.Object.Destroyしたときに、
+ /// 関連するUnityEngine.Objectを破棄するようにする。
+ /// Mesh, Material, Texture, AnimationClip, GameObject の所有者が
+ /// ImporterContext から UnityResourceDestroyer に移動する。
+ /// ImporterContext.Dispose の対象から外れる。
+ ///
+ ///
public UnityResourceDestroyer DisposeOnGameObjectDestroyed()
{
var destroyer = Root.AddComponent();
- foreach (var x in ModelOwnResources())
+ TransferOwnership(o =>
{
- destroyer.Resources.Add(x);
- }
+ destroyer.Resources.Add(o);
+ return true;
+ });
return destroyer;
}
}
diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/ImporterContextExtensions.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/ImporterContextExtensions.cs
index ef0de6ce6..b975dbfbd 100644
--- a/Assets/UniGLTF/Runtime/UniGLTF/IO/ImporterContextExtensions.cs
+++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/ImporterContextExtensions.cs
@@ -16,10 +16,21 @@ namespace UniGLTF
{
throw new Exception();
}
+ if (task.IsFaulted)
+ {
+ if (task.Exception is AggregateException ae && ae.InnerExceptions.Count == 1)
+ {
+ throw ae.InnerException;
+ }
+ else
+ {
+ throw task.Exception;
+ }
+ }
+
#if VRM_DEVELOP
Debug.Log(meassureTime.GetSpeedLog());
#endif
-
}
}
}
diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/MaterialLoader/MaterialFactory.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/MaterialLoader/MaterialFactory.cs
index fb3f6ca5f..b36126eba 100644
--- a/Assets/UniGLTF/Runtime/UniGLTF/IO/MaterialLoader/MaterialFactory.cs
+++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/MaterialLoader/MaterialFactory.cs
@@ -64,6 +64,8 @@ namespace UniGLTF
public readonly Material Asset;
public readonly bool UseExternal;
+ public bool IsSubAsset => !UseExternal;
+
public MaterialLoadInfo(Material asset, bool useExternal)
{
Asset = asset;
@@ -73,19 +75,52 @@ namespace UniGLTF
List m_materials = new List();
public IReadOnlyList Materials => m_materials;
- public void Dispose()
+ void Remove(Material material)
{
- foreach (var x in ObjectsForSubAsset())
+ var index = m_materials.FindIndex(x => x.Asset == material);
+ if (index >= 0)
{
- UnityEngine.Object.DestroyImmediate(x, true);
+ m_materials.RemoveAt(index);
+
}
}
- public IEnumerable ObjectsForSubAsset()
+ public void Dispose()
{
foreach (var x in m_materials)
{
- yield return x.Asset;
+ if (!x.UseExternal)
+ {
+ // 外部の '.asset' からロードしていない
+#if VRM_DEVELOP
+ Debug.Log($"Destroy {x.Asset}");
+#endif
+ UnityEngine.Object.DestroyImmediate(x.Asset, false);
+ }
+ }
+ }
+
+ ///
+ /// 所有権(Dispose権)を移譲する
+ ///
+ ///
+ public void TransferOwnership(TakeOwnershipFunc take)
+ {
+ var list = new List();
+ foreach (var x in m_materials)
+ {
+ if (!x.UseExternal)
+ {
+ // 外部の '.asset' からロードしていない
+ if (take(x.Asset))
+ {
+ list.Add(x.Asset);
+ }
+ }
+ }
+ foreach (var x in list)
+ {
+ Remove(x);
}
}
@@ -200,22 +235,5 @@ namespace UniGLTF
var task = DefaultCreateMaterialAsync(default(ImmediateCaller), gltf, i, null);
return task.Result;
}
-
- public IEnumerable EnumerateGetTextureparam(int i)
- {
- var m = m_gltf.materials[i];
-
- // color texture
- var colorIndex = m.pbrMetallicRoughness?.baseColorTexture?.index;
- if (colorIndex.HasValue)
- {
- yield return GetTextureParam.Create(m_gltf, i);
- }
-
- if (!glTF_KHR_materials_unlit.IsEnable(m))
- {
- // PBR
- }
- }
}
}
diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/MaterialLoader/PBRMaterialItem.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/MaterialLoader/PBRMaterialItem.cs
index 7503a6a18..4ea932bb5 100644
--- a/Assets/UniGLTF/Runtime/UniGLTF/IO/MaterialLoader/PBRMaterialItem.cs
+++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/MaterialLoader/PBRMaterialItem.cs
@@ -71,13 +71,13 @@ namespace UniGLTF
{
getTexture = (_x, _y, _z) => Task.FromResult(null);
}
- var src = gltf.materials[i];
-
- var material = MaterialFactory.CreateMaterial(i, src, ShaderName);
// PBR material
- if (src != null)
+ var material = default(Material);
+ if (i >= 0 && i < gltf.materials.Count)
{
+ var src = gltf.materials[i];
+ material = MaterialFactory.CreateMaterial(i, src, ShaderName);
if (src.pbrMetallicRoughness != null)
{
if (src.pbrMetallicRoughness.baseColorFactor != null && src.pbrMetallicRoughness.baseColorFactor.Length == 4)
@@ -214,6 +214,10 @@ namespace UniGLTF
material.SetFloat("_Mode", (float)blendMode);
}
+ else
+ {
+ material = MaterialFactory.CreateMaterial(i, null, ShaderName);
+ }
return material;
}
diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/TakeOwnershipFunc.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/TakeOwnershipFunc.cs
new file mode 100644
index 000000000..4cb91856c
--- /dev/null
+++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/TakeOwnershipFunc.cs
@@ -0,0 +1,13 @@
+namespace UniGLTF
+{
+ ///
+ /// 所有権を移動する関数。
+ ///
+ /// * 所有権が移動する。return true => ImporterContext.Dispose の対象から外れる
+ /// * 所有権が移動しない。return false => Importer.Context.Dispose でDestroyされる
+ ///
+ ///
+ /// 対象のオブジェクト
+ /// 所有権が移動したらtrue
+ public delegate bool TakeOwnershipFunc(UnityEngine.Object o);
+}
diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/TakeOwnershipFunc.cs.meta b/Assets/UniGLTF/Runtime/UniGLTF/IO/TakeOwnershipFunc.cs.meta
new file mode 100644
index 000000000..0b34ae7e0
--- /dev/null
+++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/TakeOwnershipFunc.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: ab2b998b9235dc94a90ccaf2e40a50a6
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureIO.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureIO.cs
index 61b160eed..aff199ce9 100644
--- a/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureIO.cs
+++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureIO.cs
@@ -154,7 +154,7 @@ namespace UniGLTF
);
}
- public virtual int ExportTexture(glTF gltf, int bufferIndex, Texture texture, glTFTextureTypes textureType)
+ public int ExportTexture(glTF gltf, int bufferIndex, Texture texture, glTFTextureTypes textureType)
{
var bytesWithMime = GetBytesWithMime(texture, textureType); ;
@@ -166,7 +166,7 @@ namespace UniGLTF
var imageIndex = gltf.images.Count;
gltf.images.Add(new glTFImage
{
- name = texture.name,
+ name = GetTextureParam.RemoveSuffix(texture.name),
bufferView = viewIndex,
mimeType = bytesWithMime.mine,
});
diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureLoader/GetTextureParam.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureLoader/GetTextureParam.cs
index bc3f1c5b7..b5334756d 100644
--- a/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureLoader/GetTextureParam.cs
+++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureLoader/GetTextureParam.cs
@@ -5,10 +5,50 @@ namespace UniGLTF
public struct GetTextureParam
{
public const string NORMAL_PROP = "_BumpMap";
+ public const string NORMAL_SUFFIX = ".normal";
public const string METALLIC_GLOSS_PROP = "_MetallicGlossMap";
+ public const string METALLIC_GLOSS_SUFFIX = ".metallicRoughness";
public const string OCCLUSION_PROP = "_OcclusionMap";
+ public const string OCCLUSION_SUFFIX = ".occlusion";
+
+ public static string RemoveSuffix(string src)
+ {
+ if (src.EndsWith(NORMAL_SUFFIX))
+ {
+ return src.Substring(0, src.Length - NORMAL_SUFFIX.Length);
+ }
+ else if (src.EndsWith(METALLIC_GLOSS_SUFFIX))
+ {
+ return src.Substring(0, src.Length - METALLIC_GLOSS_SUFFIX.Length);
+ }
+ else if (src.EndsWith(OCCLUSION_SUFFIX))
+ {
+ return src.Substring(0, src.Length - OCCLUSION_SUFFIX.Length);
+ }
+ else
+ {
+ return src;
+ }
+ }
+
+ readonly string m_name;
+
+ public string GltflName => m_name;
+
+ public string ConvertedName
+ {
+ get
+ {
+ switch (TextureType)
+ {
+ case METALLIC_GLOSS_PROP: return $"{m_name}{METALLIC_GLOSS_SUFFIX}";
+ case OCCLUSION_PROP: return $"{m_name}{OCCLUSION_SUFFIX}";
+ case NORMAL_PROP: return $"{m_name}{NORMAL_SUFFIX}";
+ default: return m_name;
+ }
+ }
+ }
- public readonly string Name;
public readonly string TextureType;
public readonly float MetallicFactor;
public readonly ushort? Index0;
@@ -18,13 +58,18 @@ namespace UniGLTF
public readonly ushort? Index4;
public readonly ushort? Index5;
+ ///
+ /// この2種類は変換済みをExtract
+ ///
+ public bool ExtractConverted => TextureType == OCCLUSION_PROP || TextureType == METALLIC_GLOSS_PROP;
+
public GetTextureParam(string name, string textureType, float metallicFactor, int i0, int i1, int i2, int i3, int i4, int i5)
{
if (string.IsNullOrEmpty(name))
{
throw new ArgumentNullException();
}
- Name = name;
+ m_name = name;
TextureType = textureType;
MetallicFactor = metallicFactor;
@@ -69,13 +114,13 @@ namespace UniGLTF
public static GetTextureParam CreateMetallic(glTF gltf, int textureIndex, float metallicFactor)
{
var name = gltf.textures[textureIndex].name;
- return new GetTextureParam(name + ".metallicRoughness", METALLIC_GLOSS_PROP, metallicFactor, textureIndex, default, default, default, default, default);
+ return new GetTextureParam(name, METALLIC_GLOSS_PROP, metallicFactor, textureIndex, default, default, default, default, default);
}
public static GetTextureParam CreateOcclusion(glTF gltf, int textureIndex)
{
var name = gltf.textures[textureIndex].name;
- return new GetTextureParam(name + ".occlusion", OCCLUSION_PROP, default, textureIndex, default, default, default, default, default);
+ return new GetTextureParam(name, OCCLUSION_PROP, default, textureIndex, default, default, default, default, default);
}
}
}
diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureLoader/TextureFactory.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureLoader/TextureFactory.cs
index 667b45b11..b695d701f 100644
--- a/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureLoader/TextureFactory.cs
+++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureLoader/TextureFactory.cs
@@ -24,6 +24,8 @@ namespace UniGLTF
public bool IsUsed => Flags.HasFlag(TextureLoadFlags.Used);
public bool IsExternal => Flags.HasFlag(TextureLoadFlags.External);
+ public bool IsSubAsset => IsUsed && !IsExternal;
+
public TextureLoadInfo(Texture2D texture, bool used, bool isExternal)
{
Texture = texture;
@@ -49,10 +51,15 @@ namespace UniGLTF
{
if (param.Index0.HasValue && m_externalMap != null)
{
- if (m_externalMap.TryGetValue(param.Name, out external))
+ var cacheName = param.ConvertedName;
+ if (param.TextureType == GetTextureParam.NORMAL_PROP)
{
- // Debug.Log($"use external: {param.Name}");
- m_textureCache.Add(param.Name, new TextureLoadInfo(external, used, true));
+ cacheName = param.GltflName;
+ }
+
+ if (m_externalMap.TryGetValue(cacheName, out external))
+ {
+ m_textureCache.Add(cacheName, new TextureLoadInfo(external, used, true));
return external;
}
}
@@ -77,17 +84,42 @@ namespace UniGLTF
public void Dispose()
{
- foreach (var x in ObjectsForSubAsset())
- {
- UnityEngine.Object.DestroyImmediate(x, true);
- }
- }
-
- public IEnumerable ObjectsForSubAsset()
- {
+ Action destroy = UnityResourceDestroyer.DestroyResource();
foreach (var kv in m_textureCache)
{
- yield return kv.Value.Texture;
+ if (!kv.Value.IsExternal)
+ {
+#if VRM_DEVELOP
+ Debug.Log($"Destroy {kv.Value.Texture}");
+#endif
+ destroy(kv.Value.Texture);
+ }
+ }
+ m_textureCache.Clear();
+ }
+
+ ///
+ /// 所有権(Dispose権)を移譲する
+ ///
+ ///
+ public void TransferOwnership(TakeOwnershipFunc take)
+ {
+ var keys = new List();
+ foreach (var x in m_textureCache)
+ {
+ if (x.Value.IsUsed && !x.Value.IsExternal)
+ {
+ // マテリアルから参照されていて
+ // 外部のAssetからロードしていない。
+ if (take(x.Value.Texture))
+ {
+ keys.Add(x.Key);
+ }
+ }
+ }
+ foreach (var x in keys)
+ {
+ m_textureCache.Remove(x);
}
}
@@ -118,7 +150,7 @@ namespace UniGLTF
///
public async Task GetTextureAsync(IAwaitCaller awaitCaller, glTF gltf, GetTextureParam param)
{
- if (m_textureCache.TryGetValue(param.Name, out TextureLoadInfo cacheInfo))
+ if (m_textureCache.TryGetValue(param.ConvertedName, out TextureLoadInfo cacheInfo))
{
return cacheInfo.Texture;
}
@@ -131,26 +163,12 @@ namespace UniGLTF
{
case GetTextureParam.NORMAL_PROP:
{
- if (Application.isPlaying)
- {
- var baseTexture = await GetOrCreateBaseTexture(awaitCaller, gltf, param.Index0.Value, false);
- var converted = new NormalConverter().GetImportTexture(baseTexture.Texture);
- var info = new TextureLoadInfo(converted, true, false);
- m_textureCache.Add(param.Name, info);
- return info.Texture;
- }
- else
- {
-#if UNITY_EDITOR
- var info = await LoadTextureAsync(awaitCaller, param.Index0.Value, true);
- var name = gltf.textures[param.Index0.Value].name;
- m_textureCache.Add(name, info);
-
- var textureAssetPath = AssetDatabase.GetAssetPath(info.Texture);
- TextureIO.MarkTextureAssetAsNormalMap(textureAssetPath);
-#endif
- return info.Texture;
- }
+ var baseTexture = await GetOrCreateBaseTexture(awaitCaller, gltf, param.Index0.Value, false);
+ var converted = new NormalConverter().GetImportTexture(baseTexture.Texture);
+ converted.name = param.ConvertedName;
+ var info = new TextureLoadInfo(converted, true, false);
+ m_textureCache.Add(converted.name, info);
+ return info.Texture;
}
case GetTextureParam.METALLIC_GLOSS_PROP:
@@ -158,9 +176,9 @@ namespace UniGLTF
// Bake roughnessFactor values into a texture.
var baseTexture = await GetOrCreateBaseTexture(awaitCaller, gltf, param.Index0.Value, false);
var converted = new MetallicRoughnessConverter(param.MetallicFactor).GetImportTexture(baseTexture.Texture);
- converted.name = param.Name;
+ converted.name = param.ConvertedName;
var info = new TextureLoadInfo(converted, true, false);
- m_textureCache.Add(param.Name, info);
+ m_textureCache.Add(converted.name, info);
return info.Texture;
}
@@ -168,9 +186,9 @@ namespace UniGLTF
{
var baseTexture = await GetOrCreateBaseTexture(awaitCaller, gltf, param.Index0.Value, false);
var converted = new OcclusionConverter().GetImportTexture(baseTexture.Texture);
- converted.name = param.Name;
+ converted.name = param.ConvertedName;
var info = new TextureLoadInfo(converted, true, false);
- m_textureCache.Add(param.Name, info);
+ m_textureCache.Add(converted.name, info);
return info.Texture;
}
diff --git a/Assets/UniGLTF/Runtime/UnityResourceDestroyer.cs b/Assets/UniGLTF/Runtime/UniGLTF/UnityResourceDestroyer.cs
similarity index 50%
rename from Assets/UniGLTF/Runtime/UnityResourceDestroyer.cs
rename to Assets/UniGLTF/Runtime/UniGLTF/UnityResourceDestroyer.cs
index 0882c254b..b14ae9b45 100644
--- a/Assets/UniGLTF/Runtime/UnityResourceDestroyer.cs
+++ b/Assets/UniGLTF/Runtime/UniGLTF/UnityResourceDestroyer.cs
@@ -1,4 +1,5 @@
-using System.Collections.Generic;
+using System;
+using System.Collections.Generic;
using UnityEngine;
@@ -9,7 +10,7 @@ namespace UniGLTF
///
public class UnityResourceDestroyer : MonoBehaviour
{
- List m_resources = new List