diff --git a/Assets/UniGLTF/Editor/EditorImporterContext.cs b/Assets/UniGLTF/Editor/EditorImporterContext.cs index a7af84aed..33197de02 100644 --- a/Assets/UniGLTF/Editor/EditorImporterContext.cs +++ b/Assets/UniGLTF/Editor/EditorImporterContext.cs @@ -138,7 +138,11 @@ namespace UniGLTF }; foreach (var o in ObjectsForSubAsset()) { - if (o == null) continue; + if (!string.IsNullOrEmpty(AssetDatabase.GetAssetPath(o))) + { + // already exists + continue; + } var assetPath = GetAssetPath(prefabPath, o, meshAsSubAsset); if (!assetPath.IsNull) diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureLoader/AssetTextureLoader.cs b/Assets/UniGLTF/Editor/UniGLTF/AssetTextureLoader.cs similarity index 70% rename from Assets/UniGLTF/Runtime/UniGLTF/IO/TextureLoader/AssetTextureLoader.cs rename to Assets/UniGLTF/Editor/UniGLTF/AssetTextureLoader.cs index 352f0396e..caf03659d 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureLoader/AssetTextureLoader.cs +++ b/Assets/UniGLTF/Editor/UniGLTF/AssetTextureLoader.cs @@ -1,15 +1,18 @@ -using System.Collections; -using System.Threading.Tasks; +using System.Threading.Tasks; using UnityEngine; namespace UniGLTF { -#if UNITY_EDITOR public static class AssetTextureLoader { public static Task LoadTaskAsync(UnityPath m_assetPath, - bool isLinear, glTFTextureSampler sampler) + glTF gltf, int textureIndex) { + var textureType = TextureIO.GetglTFTextureType(gltf, textureIndex); + var colorSpace = TextureIO.GetColorSpace(textureType); + var isLinear = colorSpace == RenderTextureReadWrite.Linear; + var sampler = gltf.GetSamplerFromTextureIndex(textureIndex); + // // texture from assets // @@ -19,10 +22,12 @@ namespace UniGLTF { Debug.LogWarningFormat("fail to get TextureImporter: {0}", m_assetPath); } - importer.maxTextureSize = 8192; - importer.sRGBTexture = !isLinear; - - importer.SaveAndReimport(); + else + { + importer.maxTextureSize = 8192; + importer.sRGBTexture = !isLinear; + importer.SaveAndReimport(); + } var Texture = m_assetPath.LoadAsset(); @@ -53,5 +58,4 @@ namespace UniGLTF return Task.FromResult(Texture); } } -#endif } diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureLoader/AssetTextureLoader.cs.meta b/Assets/UniGLTF/Editor/UniGLTF/AssetTextureLoader.cs.meta similarity index 100% rename from Assets/UniGLTF/Runtime/UniGLTF/IO/TextureLoader/AssetTextureLoader.cs.meta rename to Assets/UniGLTF/Editor/UniGLTF/AssetTextureLoader.cs.meta diff --git a/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/GltfScriptedImporter.cs b/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/GltfScriptedImporter.cs index 9301ea1fd..5e1a9d151 100644 --- a/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/GltfScriptedImporter.cs +++ b/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/GltfScriptedImporter.cs @@ -31,7 +31,8 @@ namespace UniGLTF var externalObjectMap = GetExternalObjectMap() .Select(kv => (kv.Key.name, kv.Value)) ; - var context = new ImporterContext(parser, externalObjectMap); + + var context = new ImporterContext(parser, null, externalObjectMap); context.InvertAxis = m_reverseAxis; context.Load(); context.ShowMeshes(); diff --git a/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/ScriptedImporterExtension.cs b/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/ScriptedImporterExtension.cs index 6328c67d8..c60524427 100644 --- a/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/ScriptedImporterExtension.cs +++ b/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/ScriptedImporterExtension.cs @@ -86,21 +86,15 @@ namespace UniGLTF } } - struct TextureInfo - { - public string Path; - public bool sRGB; - public bool IsNormalMap; - } - class TextureExtractor { GltfParser m_parser; public GltfParser Parser => m_parser; public glTF GLTF => m_parser.GLTF; + public IStorage Storage => m_parser.Storage; - public readonly List Textures = new List(); + public readonly Dictionary Textures = new Dictionary(); UnityEngine.Texture2D[] m_subAssets; string m_path; @@ -119,20 +113,38 @@ namespace UniGLTF public void Extract(GetTextureParam param) { var subAsset = m_subAssets.FirstOrDefault(x => x.name == param.Name); - var targetPath = string.Format("{0}/{1}{2}", - m_path, - param.Name, - ".png" - ); - File.WriteAllBytes(targetPath, subAsset.EncodeToPNG().ToArray()); - AssetDatabase.ImportAsset(targetPath); + string targetPath = ""; - Textures.Add(new TextureInfo + switch (param.TextureType) { - Path = targetPath, - sRGB = true, - IsNormalMap = param.TextureType == GetTextureParam.NORMAL_PROP, - }); + 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); } } @@ -163,19 +175,30 @@ namespace UniGLTF EditorApplication.delayCall += () => { - foreach (var extracted in extractor.Textures) + foreach (var kv in extractor.Textures) { - // TextureImporter - var targetTextureImporter = AssetImporter.GetAtPath(extracted.Path) as TextureImporter; - targetTextureImporter.sRGBTexture = extracted.sRGB; - if (extracted.IsNormalMap) + var targetPath = kv.Key; + var param = kv.Value; + + // TextureImporter + var targetTextureImporter = AssetImporter.GetAtPath(targetPath) as TextureImporter; + + switch (param.TextureType) { - targetTextureImporter.textureType = TextureImporterType.NormalMap; + 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(extracted.Path); + var externalObject = AssetDatabase.LoadAssetAtPath(targetPath); importer.AddRemap(new AssetImporter.SourceAssetIdentifier(typeof(UnityEngine.Texture2D), externalObject.name), externalObject); } diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/AltTask.meta b/Assets/UniGLTF/Runtime/UniGLTF/IO/AltTask.meta deleted file mode 100644 index 311da8b9e..000000000 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/AltTask.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: fb77f0e0a8472cd45a97a75e7cfbb51b -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/AltTask/AsyncMethodBuilderAttribute.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/AltTask/AsyncMethodBuilderAttribute.cs deleted file mode 100644 index 6228d159c..000000000 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/AltTask/AsyncMethodBuilderAttribute.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace System.Runtime.CompilerServices -{ - public sealed class AsyncMethodBuilderAttribute : Attribute - { - public AsyncMethodBuilderAttribute(Type builderType) - { - BuilderType = builderType; - } - - public Type BuilderType { get; } - } -} diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/AltTask/AsyncMethodBuilderAttribute.cs.meta b/Assets/UniGLTF/Runtime/UniGLTF/IO/AltTask/AsyncMethodBuilderAttribute.cs.meta deleted file mode 100644 index a12218427..000000000 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/AltTask/AsyncMethodBuilderAttribute.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 010eb0dc48af5e645af2ff8cb7f7d1d8 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/AltTask/Awaitable.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/AltTask/Awaitable.cs deleted file mode 100644 index 545082372..000000000 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/AltTask/Awaitable.cs +++ /dev/null @@ -1,155 +0,0 @@ -using System; -using System.Runtime.CompilerServices; -using System.Threading.Tasks; - - -namespace UniGLTF.AltTask -{ - /// - /// Importer 向けに Task を wrap した。 - /// - /// * EditorやUnitTestなどで、Unity の MainLoop を進行させずに 非同期を進行させることが目的 - /// - /// Global変数 SynchronizationContext.Current を一時的に変更したいのだが、 - /// システムに予期せぬ副作用を与える可能性があるのでこれを回避。 - /// UniGLTF.AltTask.TaskQueue.Current に同じ機能を与えて、タスクのPost先を制御することにした。 - /// - - public interface IAwaiter : INotifyCompletion - { - bool IsCompleted { get; } - void GetResult(); - } - - public interface IAwaitable - { - IAwaiter GetAwaiter(); - } - - public struct AwaitableMethodBuilder - { - // https://referencesource.microsoft.com/#mscorlib/system/runtime/compilerservices/AsyncMethodBuilder.cs - private AsyncTaskMethodBuilder _methodBuilder; - - public static AwaitableMethodBuilder Create() => - new AwaitableMethodBuilder { _methodBuilder = AsyncTaskMethodBuilder.Create() }; - - public void Start(ref TStateMachine stateMachine) - where TStateMachine : IAsyncStateMachine - { - _methodBuilder.Start(ref stateMachine); - } - - public void SetStateMachine(IAsyncStateMachine stateMachine) - { - _methodBuilder.SetStateMachine(stateMachine); - } - public void SetException(Exception exception) - { - _methodBuilder.SetException(exception); - } - public void SetResult() - { - _methodBuilder.SetResult(); - } - - public void AwaitOnCompleted( - ref TAwaiter awaiter, ref TStateMachine stateMachine) - where TAwaiter : INotifyCompletion - where TStateMachine : IAsyncStateMachine - { - _methodBuilder.AwaitOnCompleted(ref awaiter, ref stateMachine); - } - public void AwaitUnsafeOnCompleted( - ref TAwaiter awaiter, ref TStateMachine stateMachine) - where TAwaiter : ICriticalNotifyCompletion - where TStateMachine : IAsyncStateMachine - { - _methodBuilder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine); - } - - public Awaitable Task => new Awaitable(_methodBuilder.Task); - } - - [AsyncMethodBuilder(typeof(AwaitableMethodBuilder))] - public struct Awaitable : IAwaitable - { - private Task _task; - - public Awaitable(Task task) - { - _task = task; - if (_task.Exception != null) - { - throw _task.Exception; - } - } - - public bool IsCompleted => _task.IsCompleted; - - public Exception Exception => _task.Exception; - - public IAwaiter GetAwaiter() - { - return new Awaiter(this); - } - - public void ContinueWith(Action action) - { - _task.ContinueWith((Task, _) => - { - action(); - }, null); - } - - public static Awaitable Run(Func action) - { - return new Awaitable(Task.Run(action)); - } - - public static Awaitable Run(Action action) - { - return new Awaitable(Task.Run(action)); - } - - public static Awaitable FromResult(T result) - { - return new Awaitable(Task.FromResult(result)); - } - } - - public class Awaiter : IAwaiter - { - Awaitable m_task; - - public bool IsCompleted - { - get - { - return m_task.IsCompleted; - } - } - - public void GetResult() - { - if (m_task.Exception != null) - { - throw m_task.Exception; - } - } - - public void OnCompleted(Action continuation) - { - var context = TaskQueue.Current; - this.m_task.ContinueWith(() => - { - context.Post(_ => continuation(), null); - }); - } - - public Awaiter(Awaitable task) - { - m_task = task; - } - } -} diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/AltTask/Awaitable.cs.meta b/Assets/UniGLTF/Runtime/UniGLTF/IO/AltTask/Awaitable.cs.meta deleted file mode 100644 index 4b6350805..000000000 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/AltTask/Awaitable.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 4a5d6155408ca734297a104d9e590d1f -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/AltTask/GenericAwaitable.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/AltTask/GenericAwaitable.cs deleted file mode 100644 index 87326a28f..000000000 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/AltTask/GenericAwaitable.cs +++ /dev/null @@ -1,138 +0,0 @@ -using System; -using System.Runtime.CompilerServices; -using System.Threading.Tasks; - - -namespace UniGLTF.AltTask -{ - public interface IAwaiter : INotifyCompletion - { - bool IsCompleted { get; } - T GetResult(); - } - - public interface IAwaitable - { - IAwaiter GetAwaiter(); - } - - - public struct ExplicitTaskMethodBuilder - { - // https://referencesource.microsoft.com/#mscorlib/system/runtime/compilerservices/AsyncMethodBuilder.cs - private AsyncTaskMethodBuilder _methodBuilder; - - public static ExplicitTaskMethodBuilder Create() => - new ExplicitTaskMethodBuilder { _methodBuilder = AsyncTaskMethodBuilder.Create() }; - - public void Start(ref TStateMachine stateMachine) - where TStateMachine : IAsyncStateMachine - { - _methodBuilder.Start(ref stateMachine); - } - - public void SetStateMachine(IAsyncStateMachine stateMachine) - { - _methodBuilder.SetStateMachine(stateMachine); - } - public void SetException(Exception exception) - { - _methodBuilder.SetException(exception); - } - public void SetResult(T result) - { - _methodBuilder.SetResult(result); - } - - public void AwaitOnCompleted( - ref TAwaiter awaiter, ref TStateMachine stateMachine) - where TAwaiter : INotifyCompletion - where TStateMachine : IAsyncStateMachine - { - _methodBuilder.AwaitOnCompleted(ref awaiter, ref stateMachine); - } - public void AwaitUnsafeOnCompleted( - ref TAwaiter awaiter, ref TStateMachine stateMachine) - where TAwaiter : ICriticalNotifyCompletion - where TStateMachine : IAsyncStateMachine - { - _methodBuilder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine); - } - - public Awaitable Task => new Awaitable(_methodBuilder.Task); - } - - [AsyncMethodBuilder(typeof(ExplicitTaskMethodBuilder<>))] - public struct Awaitable : IAwaitable - { - private Task _task; - - public Awaitable(Task task) - { - _task = task; - if (_task.Exception != null) - { - throw _task.Exception; - } - } - - public bool IsCompleted => _task.IsCompleted; - public T Result => _task.Result; - public Exception Exception => _task.Exception; - - public IAwaiter GetAwaiter() - { - return new Awaiter(this); - } - - public void ContinueWith(Action action) - { - _task.ContinueWith((Task, _) => - { - action(); - }, null); - } - - public static Awaitable Delay() - { - var task = Task.FromResult(default); - return new Awaitable(task); - } - } - - public class Awaiter : IAwaiter - { - Awaitable m_task; - - public bool IsCompleted - { - get - { - return m_task.IsCompleted; - } - } - - public T GetResult() - { - if (m_task.Exception != null) - { - throw m_task.Exception; - } - return m_task.Result; - } - - public void OnCompleted(Action continuation) - { - var context = TaskQueue.Current; - this.m_task.ContinueWith(() => - { - context.Post(_ => continuation(), null); - }); - } - - public Awaiter(Awaitable task) - { - m_task = task; - } - } -} diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/AltTask/GenericAwaitable.cs.meta b/Assets/UniGLTF/Runtime/UniGLTF/IO/AltTask/GenericAwaitable.cs.meta deleted file mode 100644 index 3e045b411..000000000 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/AltTask/GenericAwaitable.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 58f3a0011aba9ec4cb9d57a9efd35524 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/AltTask/NextFrameAwaitable.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/AltTask/NextFrameAwaitable.cs deleted file mode 100644 index f1be89203..000000000 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/AltTask/NextFrameAwaitable.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System; - -namespace UniGLTF.AltTask -{ - public static class NextFrameAwaitable - { - // TODO - // loop スレッド使わないようにしたい - public static Awaitable Create() - { - return Awaitable.Run(() => - { - System.Threading.Thread.Sleep(10); - }); - } - } -} diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/AltTask/TaskQueue.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/AltTask/TaskQueue.cs deleted file mode 100644 index 4446f232d..000000000 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/AltTask/TaskQueue.cs +++ /dev/null @@ -1,60 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Threading; - -namespace UniGLTF.AltTask -{ - public class TaskQueue : SynchronizationContext, IDisposable - { - [ThreadStatic] - static TaskQueue s_queue; - - public new static SynchronizationContext Current - { - get - { - if (s_queue == null) - { - return System.Threading.SynchronizationContext.Current; - } - else - { - return s_queue; - } - } - } - - public override void Post(SendOrPostCallback d, object state) - { - m_tasks.Enqueue(() => d(state)); - } - - Queue m_tasks = new Queue(); - - public static TaskQueue Create() - { - return new TaskQueue(); - } - - TaskQueue() - { - s_queue = this; - } - - public void Dispose() - { - s_queue = null; - } - - public bool ExecuteOneCallback() - { - if (m_tasks.Count == 0) - { - return false; - } - var task = m_tasks.Dequeue(); - task(); - return true; - } - } -} diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/AltTask/TaskQueue.cs.meta b/Assets/UniGLTF/Runtime/UniGLTF/IO/AltTask/TaskQueue.cs.meta deleted file mode 100644 index fef1e0f9d..000000000 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/AltTask/TaskQueue.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 6a65e00e71613c24e865e35173c30be0 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/IAwaitCaller.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/IAwaitCaller.cs new file mode 100644 index 000000000..68258e8a6 --- /dev/null +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/IAwaitCaller.cs @@ -0,0 +1,82 @@ +using System; +using System.Threading; +using System.Threading.Tasks; + +namespace UniGLTF +{ + /// + /// ImporterContext の 非同期実行 LoadAsync を補助する。 + /// この関数を経由して await すること。 + /// そうしないと、同期実行 Load 時にデッドロックに陥るかもしれない。 + /// (SynchronizationContext に Post された 継続が再開されない) + /// + public interface IAwaitCaller + { + /// + /// フレームレートを維持するために1フレーム待つ + /// + /// + Task NextFrame(); + + /// + /// 非同期に実行して、終了を待つ + /// + /// + /// + Task Run(Action action); + + /// + /// 非同期に実行して、終了を待つ + /// + /// + /// + /// + Task Run(Func action); + } + + /// + /// 同期実行 + /// + public struct ImmediateCaller : IAwaitCaller + { + public Task NextFrame() + { + return Task.FromResult(null); + } + + public Task Run(Action action) + { + action(); + return Task.FromResult(null); + } + + public Task Run(Func action) + { + return Task.FromResult(action()); + } + } + + /// + /// 非同期実行 + /// + public class TaskCaller : IAwaitCaller + { + public Task NextFrame() + { + return Task.Run(() => + { + // Thread.Sleep(10); + }); + } + + public Task Run(Action action) + { + return Task.Run(action); + } + + public Task Run(Func action) + { + return Task.Run(action); + } + } +} diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/AltTask/NextFrameAwaitable.cs.meta b/Assets/UniGLTF/Runtime/UniGLTF/IO/IAwaitCaller.cs.meta similarity index 83% rename from Assets/UniGLTF/Runtime/UniGLTF/IO/AltTask/NextFrameAwaitable.cs.meta rename to Assets/UniGLTF/Runtime/UniGLTF/IO/IAwaitCaller.cs.meta index 498037b0f..91b41274c 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/AltTask/NextFrameAwaitable.cs.meta +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/IAwaitCaller.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 81795a4f6e605d74787f604354a8565f +guid: 9cd79193a3dfa7148bb76882f4988071 MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/ImporterContext.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/ImporterContext.cs index 9338c3138..305a74182 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/ImporterContext.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/ImporterContext.cs @@ -2,7 +2,7 @@ using System.Linq; using System.Collections.Generic; using UnityEngine; -using UniGLTF.AltTask; +using System.Threading.Tasks; namespace UniGLTF { @@ -37,10 +37,26 @@ namespace UniGLTF TextureFactory m_textureFactory; public TextureFactory TextureFactory => m_textureFactory; - public ImporterContext(GltfParser parser, IEnumerable<(string, UnityEngine.Object)> externalObjectMap = null) + IAwaitCaller m_awaitCaller; + + public ImporterContext(GltfParser parser, + LoadTextureAsyncFunc loadTextureAsync = null, + IEnumerable<(string, UnityEngine.Object)> externalObjectMap = null) { m_parser = parser; - m_textureFactory = new TextureFactory(GLTF, Storage, externalObjectMap); + if (loadTextureAsync == null) + { +#if UNIGLTF_USE_WEBREQUEST_TEXTURELOADER + loadTextureAsync = (awaitCaller, index, used) => UnityWebRequestTextureLoader.LoadTextureAsync(index); +#else + loadTextureAsync = async (awaitCaller, index, used) => + { + var texture = await GltfTextureLoader.LoadTextureAsync(awaitCaller, GLTF, Storage, index); + return new TextureLoadInfo(texture, used, false); + }; +#endif + } + m_textureFactory = new TextureFactory(loadTextureAsync, externalObjectMap); m_materialFactory = new MaterialFactory(GLTF, Storage, externalObjectMap); } @@ -60,8 +76,14 @@ namespace UniGLTF public Axises InvertAxis = Axises.Z; #region Load. Build unity objects - public virtual async Awaitable LoadAsync(Func MeasureTime = null) + public virtual async Task LoadAsync(IAwaitCaller awaitCaller = null, Func MeasureTime = null) { + if (awaitCaller == null) + { + awaitCaller = new TaskCaller(); + } + m_awaitCaller = awaitCaller; + if (MeasureTime == null) { MeasureTime = new ImporterContextSpeedLog().MeasureTime; @@ -94,7 +116,7 @@ namespace UniGLTF using (MeasureTime("LoadMaterials")) { - await m_materialFactory.LoadMaterialsAsync(m_textureFactory.GetTextureAsync); + await m_materialFactory.LoadMaterialsAsync(m_awaitCaller, m_textureFactory.GetTextureAsync); } var meshImporter = new MeshImporter(); @@ -116,7 +138,7 @@ namespace UniGLTF Nodes.Add(NodeImporter.ImportNode(GLTF.nodes[i], i).transform); } } - await NextFrameAwaitable.Create(); + await m_awaitCaller.NextFrame(); using (MeasureTime("BuildHierarchy")) { @@ -141,26 +163,26 @@ namespace UniGLTF t.SetParent(Root.transform, false); } } - await NextFrameAwaitable.Create(); + await m_awaitCaller.NextFrame(); using (MeasureTime("AnimationImporter")) { AnimationImporter.Import(this); } - await OnLoadModel(MeasureTime); + await OnLoadModel(m_awaitCaller, MeasureTime); } - protected virtual async Awaitable OnLoadModel(Func MeasureTime) + protected virtual async Task OnLoadModel(IAwaitCaller awaitCaller, Func MeasureTime) { // do nothing } - async Awaitable BuildMeshAsync(Func MeasureTime, MeshImporter.MeshContext x, int i) + async Task BuildMeshAsync(Func MeasureTime, MeshImporter.MeshContext x, int i) { using (MeasureTime("BuildMesh")) { - var meshWithMaterials = await MeshImporter.BuildMeshAsync(MaterialFactory, x); + var meshWithMaterials = await MeshImporter.BuildMeshAsync(m_awaitCaller, MaterialFactory, x); var mesh = meshWithMaterials.Mesh; // mesh name diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/ImporterContextExtensions.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/ImporterContextExtensions.cs index 5eaf1915a..ef0de6ce6 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/ImporterContextExtensions.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/ImporterContextExtensions.cs @@ -1,5 +1,4 @@ -using System.IO; -using UniGLTF.AltTask; +using System; using UnityEngine; namespace UniGLTF @@ -12,21 +11,15 @@ namespace UniGLTF public static void Load(this ImporterContext self) { var meassureTime = new ImporterContextSpeedLog(); - using (var queue = TaskQueue.Create()) + var task = self.LoadAsync(default(ImmediateCaller), meassureTime.MeasureTime); + if (!task.IsCompleted) { - var task = self.LoadAsync(meassureTime.MeasureTime); - - // 中断された await を消化する - while (!task.IsCompleted) - { - // execute synchronous - queue.ExecuteOneCallback(); - } + throw new 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 041122e9c..d44492f48 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/MaterialLoader/MaterialFactory.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/MaterialLoader/MaterialFactory.cs @@ -1,8 +1,8 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Threading.Tasks; using UnityEngine; -using UniGLTF.AltTask; namespace UniGLTF { @@ -41,7 +41,7 @@ namespace UniGLTF } } - public delegate Awaitable CreateMaterialAsyncFunc(glTF gltf, int i, GetTextureAsyncFunc getTexture); + public delegate Task CreateMaterialAsyncFunc(IAwaitCaller awaitCaller, glTF gltf, int i, GetTextureAsyncFunc getTexture); CreateMaterialAsyncFunc m_createMaterialAsync; public CreateMaterialAsyncFunc CreateMaterialAsync { @@ -101,12 +101,12 @@ namespace UniGLTF /// /// /// - public async Awaitable LoadMaterialsAsync(GetTextureAsyncFunc getTexture) + public async Task LoadMaterialsAsync(IAwaitCaller awaitCaller, GetTextureAsyncFunc getTexture) { if (m_gltf.materials == null || m_gltf.materials.Count == 0) { // no material. work around. - var material = await CreateMaterialAsync(m_gltf, 0, getTexture); + var material = await CreateMaterialAsync(awaitCaller, m_gltf, 0, getTexture); m_materials.Add(new MaterialLoadInfo(material, false)); return; } @@ -119,7 +119,7 @@ namespace UniGLTF continue; } - material = await CreateMaterialAsync(m_gltf, i, getTexture); + material = await CreateMaterialAsync(awaitCaller, m_gltf, i, getTexture); m_materials.Add(new MaterialLoadInfo(material, false)); } } @@ -161,22 +161,22 @@ namespace UniGLTF } } - public static Awaitable DefaultCreateMaterialAsync(glTF gltf, int i, GetTextureAsyncFunc getTexture) + public static Task DefaultCreateMaterialAsync(IAwaitCaller awaitCaller, glTF gltf, int i, GetTextureAsyncFunc getTexture) { if (i < 0 || i >= gltf.materials.Count) { UnityEngine.Debug.LogWarning("glTFMaterial is empty"); - return PBRMaterialItem.CreateAsync(gltf, i, getTexture); + return PBRMaterialItem.CreateAsync(awaitCaller, gltf, i, getTexture); } var x = gltf.materials[i]; if (glTF_KHR_materials_unlit.IsEnable(x)) { var hasVertexColor = gltf.MaterialHasVertexColor(i); - return UnlitMaterialItem.CreateAsync(gltf, i, getTexture, hasVertexColor); + return UnlitMaterialItem.CreateAsync(awaitCaller, gltf, i, getTexture, hasVertexColor); } - return PBRMaterialItem.CreateAsync(gltf, i, getTexture); + return PBRMaterialItem.CreateAsync(awaitCaller, gltf, i, getTexture); } /// @@ -192,7 +192,7 @@ namespace UniGLTF { materials = new System.Collections.Generic.List { material }, }; - var task = DefaultCreateMaterialAsync(gltf, i, null); + var task = DefaultCreateMaterialAsync(default(ImmediateCaller), gltf, i, null); return task.Result; } diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/MaterialLoader/PBRMaterialItem.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/MaterialLoader/PBRMaterialItem.cs index cf3605552..7503a6a18 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/MaterialLoader/PBRMaterialItem.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/MaterialLoader/PBRMaterialItem.cs @@ -1,5 +1,5 @@  -using UniGLTF.AltTask; +using System.Threading.Tasks; using UnityEngine; namespace UniGLTF @@ -65,11 +65,11 @@ namespace UniGLTF return GetTextureParam.CreateNormal(gltf, src.normalTexture.index); } - public static async Awaitable CreateAsync(glTF gltf, int i, GetTextureAsyncFunc getTexture) + public static async Task CreateAsync(IAwaitCaller awaitCaller, glTF gltf, int i, GetTextureAsyncFunc getTexture) { if (getTexture == null) { - getTexture = (_x, _y) => Awaitable.FromResult(null); + getTexture = (_x, _y, _z) => Task.FromResult(null); } var src = gltf.materials[i]; @@ -88,7 +88,7 @@ namespace UniGLTF if (src.pbrMetallicRoughness.baseColorTexture != null && src.pbrMetallicRoughness.baseColorTexture.index != -1) { - material.mainTexture = await getTexture(gltf, BaseColorTexture(gltf, src)); + material.mainTexture = await getTexture(awaitCaller, gltf, BaseColorTexture(gltf, src)); // Texture Offset and Scale MaterialFactory.SetTextureOffsetAndScale(material, src.pbrMetallicRoughness.baseColorTexture, "_MainTex"); @@ -98,7 +98,7 @@ namespace UniGLTF { material.EnableKeyword("_METALLICGLOSSMAP"); - var texture = await getTexture(gltf, MetallicRoughnessTexture(gltf, src)); + var texture = await getTexture(awaitCaller, gltf, MetallicRoughnessTexture(gltf, src)); if (texture != null) { material.SetTexture(GetTextureParam.METALLIC_GLOSS_PROP, texture); @@ -121,7 +121,7 @@ namespace UniGLTF if (src.normalTexture != null && src.normalTexture.index != -1) { material.EnableKeyword("_NORMALMAP"); - var texture = await getTexture(gltf, NormalTexture(gltf, src)); + var texture = await getTexture(awaitCaller, gltf, NormalTexture(gltf, src)); if (texture != null) { material.SetTexture(GetTextureParam.NORMAL_PROP, texture); @@ -134,7 +134,7 @@ namespace UniGLTF if (src.occlusionTexture != null && src.occlusionTexture.index != -1) { - var texture = await getTexture(gltf, OcclusionTexture(gltf, src)); + var texture = await getTexture(awaitCaller, gltf, OcclusionTexture(gltf, src)); if (texture != null) { material.SetTexture(GetTextureParam.OCCLUSION_PROP, texture); @@ -158,7 +158,7 @@ namespace UniGLTF if (src.emissiveTexture != null && src.emissiveTexture.index != -1) { - var texture = await getTexture(gltf, GetTextureParam.Create(gltf, src.emissiveTexture.index)); + var texture = await getTexture(awaitCaller, gltf, GetTextureParam.Create(gltf, src.emissiveTexture.index)); if (texture != null) { material.SetTexture("_EmissionMap", texture); diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/MaterialLoader/UnlitMaterialItem.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/MaterialLoader/UnlitMaterialItem.cs index cd382d012..2cca1aab4 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/MaterialLoader/UnlitMaterialItem.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/MaterialLoader/UnlitMaterialItem.cs @@ -1,4 +1,5 @@ -using UniGLTF.AltTask; + +using System.Threading.Tasks; using UnityEngine; namespace UniGLTF @@ -7,11 +8,11 @@ namespace UniGLTF { public const string ShaderName = "UniGLTF/UniUnlit"; - public static async Awaitable CreateAsync(glTF gltf, int i, GetTextureAsyncFunc getTexture, bool hasVertexColor) + public static async Task CreateAsync(IAwaitCaller awaitCaller, glTF gltf, int i, GetTextureAsyncFunc getTexture, bool hasVertexColor) { if (getTexture == null) { - getTexture = (_x, _y) => Awaitable.FromResult(default); + getTexture = (_x, _y, _z) => Task.FromResult(default); } var src = gltf.materials[i]; @@ -20,7 +21,7 @@ namespace UniGLTF // texture if (src.pbrMetallicRoughness.baseColorTexture != null) { - material.mainTexture = await getTexture(gltf, GetTextureParam.Create(gltf, src.pbrMetallicRoughness.baseColorTexture.index)); + material.mainTexture = await getTexture(awaitCaller, gltf, GetTextureParam.Create(gltf, src.pbrMetallicRoughness.baseColorTexture.index)); // Texture Offset and Scale MaterialFactory.SetTextureOffsetAndScale(material, src.pbrMetallicRoughness.baseColorTexture, "_MainTex"); diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshImporter.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshImporter.cs index f5f535858..00b59863b 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshImporter.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshImporter.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; -using UniGLTF.AltTask; +using System.Threading.Tasks; using UnityEngine; @@ -670,15 +670,15 @@ namespace UniGLTF } } - public static async Awaitable BuildMeshAsync(MaterialFactory ctx, MeshImporter.MeshContext meshContext) + public static async Task BuildMeshAsync(IAwaitCaller awaitCaller, MaterialFactory ctx, MeshImporter.MeshContext meshContext) { var (mesh, recalculateTangents) = _BuildMesh(meshContext); if (recalculateTangents) { - await NextFrameAwaitable.Create(); + await awaitCaller.NextFrame(); mesh.RecalculateTangents(); - await NextFrameAwaitable.Create(); + await awaitCaller.NextFrame(); } // 先にすべてのマテリアルを作成済みなのでテクスチャーは生成済み。Resultを使ってよい @@ -688,7 +688,7 @@ namespace UniGLTF Materials = meshContext.MaterialIndices.Select(x => ctx.GetMaterial(x)).ToArray() }; - await NextFrameAwaitable.Create(); + await awaitCaller.NextFrame(); if (meshContext.BlendShapes.Count > 0) { var emptyVertices = new Vector3[mesh.vertexCount]; diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureLoader/GltfTextureLoader.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureLoader/GltfTextureLoader.cs index 5169e5f70..d700a8edf 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureLoader/GltfTextureLoader.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureLoader/GltfTextureLoader.cs @@ -1,5 +1,5 @@ using System; -using UniGLTF.AltTask; +using System.Threading.Tasks; using UnityEngine; namespace UniGLTF @@ -24,9 +24,9 @@ namespace UniGLTF } } - public static async Awaitable LoadTextureAsync(glTF gltf, IStorage storage, int textureIndex) + public static async Task LoadTextureAsync(IAwaitCaller awaitCaller, glTF gltf, IStorage storage, int textureIndex) { - var imageBytes = await Awaitable.Run(() => + var imageBytes = await awaitCaller.Run(() => { var imageIndex = gltf.textures[textureIndex].source; var segments = gltf.GetImageBytes(storage, imageIndex); diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureLoader/TextureFactory.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureLoader/TextureFactory.cs index 1b0ff44d1..667b45b11 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureLoader/TextureFactory.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureLoader/TextureFactory.cs @@ -1,8 +1,8 @@ using System; using System.Collections.Generic; -using UniGLTF.AltTask; using UnityEngine; using System.Linq; +using System.Threading.Tasks; #if UNITY_EDITOR using UnityEditor; #endif @@ -40,11 +40,10 @@ namespace UniGLTF } } - public delegate Awaitable GetTextureAsyncFunc(glTF gltf, GetTextureParam param); + public delegate Task LoadTextureAsyncFunc(IAwaitCaller awaitCaller, int index, bool used); + public delegate Task GetTextureAsyncFunc(IAwaitCaller awaitCaller, glTF gltf, GetTextureParam param); public class TextureFactory : IDisposable { - glTF m_gltf; - IStorage m_storage; Dictionary m_externalMap; public bool TryGetExternal(GetTextureParam param, bool used, out Texture2D external) { @@ -63,11 +62,10 @@ namespace UniGLTF public UnityPath ImageBaseDir { get; set; } - public TextureFactory(glTF gltf, IStorage storage, - IEnumerable<(string, UnityEngine.Object)> externalMap) + public TextureFactory(LoadTextureAsyncFunc loadTextureAsync, + IEnumerable<(string, UnityEngine.Object)> externalMap) { - m_gltf = gltf; - m_storage = storage; + LoadTextureAsync = loadTextureAsync; if (externalMap != null) { m_externalMap = externalMap @@ -97,22 +95,14 @@ namespace UniGLTF public IEnumerable Textures => m_textureCache.Values; - public virtual async Awaitable LoadTextureAsync(int index, bool used) - { -#if UNIGLTF_USE_WEBREQUEST_TEXTURELOADER - return UnityWebRequestTextureLoader.LoadTextureAsync(index); -#else - var texture = await GltfTextureLoader.LoadTextureAsync(m_gltf, m_storage, index); - return new TextureLoadInfo(texture, used, false); -#endif - } + public LoadTextureAsyncFunc LoadTextureAsync; - async Awaitable GetOrCreateBaseTexture(glTF gltf, int textureIndex, bool used) + async Task GetOrCreateBaseTexture(IAwaitCaller awaitCaller, glTF gltf, int textureIndex, bool used) { var name = gltf.textures[textureIndex].name; if (!m_textureCache.TryGetValue(name, out TextureLoadInfo cacheInfo)) { - cacheInfo = await LoadTextureAsync(textureIndex, used); + cacheInfo = await LoadTextureAsync(awaitCaller, textureIndex, used); m_textureCache.Add(name, cacheInfo); } return cacheInfo; @@ -126,7 +116,7 @@ namespace UniGLTF /// METALLIC_GLOSS_PROPの追加パラメーター /// gltf の texture index /// - public async Awaitable GetTextureAsync(glTF gltf, GetTextureParam param) + public async Task GetTextureAsync(IAwaitCaller awaitCaller, glTF gltf, GetTextureParam param) { if (m_textureCache.TryGetValue(param.Name, out TextureLoadInfo cacheInfo)) { @@ -143,7 +133,7 @@ namespace UniGLTF { if (Application.isPlaying) { - var baseTexture = await GetOrCreateBaseTexture(gltf, param.Index0.Value, false); + 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); @@ -152,7 +142,7 @@ namespace UniGLTF else { #if UNITY_EDITOR - var info = await LoadTextureAsync(param.Index0.Value, true); + var info = await LoadTextureAsync(awaitCaller, param.Index0.Value, true); var name = gltf.textures[param.Index0.Value].name; m_textureCache.Add(name, info); @@ -166,7 +156,7 @@ namespace UniGLTF case GetTextureParam.METALLIC_GLOSS_PROP: { // Bake roughnessFactor values into a texture. - var baseTexture = await GetOrCreateBaseTexture(gltf, param.Index0.Value, false); + var baseTexture = await GetOrCreateBaseTexture(awaitCaller, gltf, param.Index0.Value, false); var converted = new MetallicRoughnessConverter(param.MetallicFactor).GetImportTexture(baseTexture.Texture); converted.name = param.Name; var info = new TextureLoadInfo(converted, true, false); @@ -176,7 +166,7 @@ namespace UniGLTF case GetTextureParam.OCCLUSION_PROP: { - var baseTexture = await GetOrCreateBaseTexture(gltf, param.Index0.Value, false); + var baseTexture = await GetOrCreateBaseTexture(awaitCaller, gltf, param.Index0.Value, false); var converted = new OcclusionConverter().GetImportTexture(baseTexture.Texture); converted.name = param.Name; var info = new TextureLoadInfo(converted, true, false); @@ -186,7 +176,7 @@ namespace UniGLTF default: { - var baseTexture = await GetOrCreateBaseTexture(gltf, param.Index0.Value, true); + var baseTexture = await GetOrCreateBaseTexture(awaitCaller, gltf, param.Index0.Value, true); return baseTexture.Texture; } diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureLoader/UnityWebRequestTextureLoader.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureLoader/UnityWebRequestTextureLoader.cs index 5712e8161..329bc5cbc 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureLoader/UnityWebRequestTextureLoader.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureLoader/UnityWebRequestTextureLoader.cs @@ -32,7 +32,7 @@ namespace UniGLTF } } - string m_textureName; + string m_textureName = default; public void ProcessOnAnyThread() { } diff --git a/Assets/VRM.Samples/Scripts/ViewerUI.cs b/Assets/VRM.Samples/Scripts/ViewerUI.cs index 3905ad375..7c83452fa 100644 --- a/Assets/VRM.Samples/Scripts/ViewerUI.cs +++ b/Assets/VRM.Samples/Scripts/ViewerUI.cs @@ -1,8 +1,8 @@ using System; using System.IO; using System.Linq; +using System.Threading.Tasks; using UniGLTF; -using UniGLTF.AltTask; using UniHumanoid; using UnityEngine; using UnityEngine.UI; @@ -87,9 +87,9 @@ namespace VRM.Samples m_textDistributionOther.text = ""; } - public async Awaitable UpdateMetaAsync(VRMImporterContext context) + public async Task UpdateMetaAsync(VRMImporterContext context) { - var meta = await context.ReadMetaAsync(true); + var meta = await context.ReadMetaAsync(default(TaskCaller), true); m_textModelTitle.text = meta.Title; m_textModelVersion.text = meta.Version; diff --git a/Assets/VRM/Editor/Format/vrmAssetPostprocessor.cs b/Assets/VRM/Editor/Format/vrmAssetPostprocessor.cs index a56705d04..d48480048 100644 --- a/Assets/VRM/Editor/Format/vrmAssetPostprocessor.cs +++ b/Assets/VRM/Editor/Format/vrmAssetPostprocessor.cs @@ -51,7 +51,15 @@ namespace VRM var prefabPath = path.Parent.Child(path.FileNameWithoutExtension + ".prefab"); // save texture assets ! - var context = new VRMImporterContext(parser); + 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); diff --git a/Assets/VRM/Runtime/IO/VRMImporterContext.cs b/Assets/VRM/Runtime/IO/VRMImporterContext.cs index 312191a52..cf6fa6d51 100644 --- a/Assets/VRM/Runtime/IO/VRMImporterContext.cs +++ b/Assets/VRM/Runtime/IO/VRMImporterContext.cs @@ -4,7 +4,7 @@ using System.Collections.Generic; using UniGLTF; using UnityEngine; using UniJSON; -using UniGLTF.AltTask; +using System.Threading.Tasks; namespace VRM { @@ -14,14 +14,14 @@ namespace VRM { public VRM.glTF_VRM_extensions VRM { get; private set; } - public VRMImporterContext(GltfParser parser) : base(parser) + public VRMImporterContext(GltfParser parser, UniGLTF.LoadTextureAsyncFunc asyncTextureLoader = null) : base(parser, asyncTextureLoader) { // parse VRM part if (glTF_VRM_extensions.TryDeserilize(GLTF.extensions, out glTF_VRM_extensions vrm)) { VRM = vrm; // override material importer - MaterialFactory.CreateMaterialAsync = new VRMMaterialImporter(VRM.materialProperties).CreateMaterial; + MaterialFactory.CreateMaterialAsync = new VRMMaterialImporter(VRM.materialProperties).CreateMaterialAsync; } else { @@ -30,7 +30,7 @@ namespace VRM } #region OnLoad - protected override async Awaitable OnLoadModel(Func MeasureTime) + protected override async Task OnLoadModel(IAwaitCaller awaitCaller, Func MeasureTime) { Root.name = "VRM"; @@ -38,26 +38,26 @@ namespace VRM { await LoadMetaAsync(); } - await NextFrameAwaitable.Create(); + await awaitCaller.NextFrame(); using (MeasureTime("VRM LoadHumanoid")) { LoadHumanoid(); } - await NextFrameAwaitable.Create(); + await awaitCaller.NextFrame(); using (MeasureTime("VRM LoadBlendShapeMaster")) { LoadBlendShapeMaster(); } - await NextFrameAwaitable.Create(); + await awaitCaller.NextFrame(); using (MeasureTime("VRM LoadSecondary")) { VRMSpringUtility.LoadSecondary(Root.transform, Nodes, VRM.secondaryAnimation); } - await NextFrameAwaitable.Create(); + await awaitCaller.NextFrame(); using (MeasureTime("VRM LoadFirstPerson")) { @@ -65,7 +65,7 @@ namespace VRM } } - async Awaitable LoadMetaAsync() + async Task LoadMetaAsync() { var meta = await ReadMetaAsync(); var _meta = Root.AddComponent(); @@ -273,8 +273,13 @@ namespace VRM public BlendShapeAvatar BlendShapeAvatar; public VRMMetaObject Meta; - public async Awaitable ReadMetaAsync(bool createThumbnail = false) + public async Task ReadMetaAsync(IAwaitCaller awaitCaller = null, bool createThumbnail = false) { + if (awaitCaller == null) + { + awaitCaller = default(ImmediateCaller); + } + var meta = ScriptableObject.CreateInstance(); meta.name = "Meta"; meta.ExporterVersion = VRM.exporterVersion; @@ -285,7 +290,7 @@ namespace VRM meta.ContactInformation = gltfMeta.contactInformation; meta.Reference = gltfMeta.reference; meta.Title = gltfMeta.title; - meta.Thumbnail = await TextureFactory.GetTextureAsync(GLTF, GetTextureParam.Create(GLTF, gltfMeta.texture)); + meta.Thumbnail = await TextureFactory.GetTextureAsync(awaitCaller, GLTF, GetTextureParam.Create(GLTF, gltfMeta.texture)); meta.AllowedUser = gltfMeta.allowedUser; meta.ViolentUssage = gltfMeta.violentUssage; meta.SexualUssage = gltfMeta.sexualUssage; diff --git a/Assets/VRM/Runtime/IO/VRMMaterialImporter.cs b/Assets/VRM/Runtime/IO/VRMMaterialImporter.cs index b18313c66..ca927176e 100644 --- a/Assets/VRM/Runtime/IO/VRMMaterialImporter.cs +++ b/Assets/VRM/Runtime/IO/VRMMaterialImporter.cs @@ -4,7 +4,6 @@ using UnityEngine; using System.Linq; using System; using System.Threading.Tasks; -using UniGLTF.AltTask; namespace VRM { @@ -22,7 +21,7 @@ namespace VRM "VRM/UnlitTransparentZWrite", }; - public static async Awaitable CreateAsync(glTF gltf, int m_index, glTF_VRM_Material vrmMaterial, GetTextureAsyncFunc getTexture) + public static async Task CreateAsync(IAwaitCaller awaitCaller, glTF gltf, int m_index, glTF_VRM_Material vrmMaterial, GetTextureAsyncFunc getTexture) { var item = vrmMaterial; var shaderName = item.shader; @@ -40,7 +39,7 @@ namespace VRM { Debug.LogWarningFormat("unknown shader {0}.", shaderName); } - return await MaterialFactory.DefaultCreateMaterialAsync(gltf, m_index, getTexture); + return await MaterialFactory.DefaultCreateMaterialAsync(awaitCaller, gltf, m_index, getTexture); } // @@ -72,7 +71,7 @@ namespace VRM foreach (var kv in item.textureProperties) { var param = GetTextureParam.Create(gltf, kv.Value, kv.Key); - var texture = await getTexture(gltf, param); + var texture = await getTexture(awaitCaller, gltf, param); if (texture != null) { material.SetTexture(kv.Key, texture); @@ -113,15 +112,15 @@ namespace VRM m_materials = materials; } - public Awaitable CreateMaterial(glTF gltf, int i, GetTextureAsyncFunc getTexture) + public Task CreateMaterialAsync(IAwaitCaller awaitCaller, glTF gltf, int i, GetTextureAsyncFunc getTexture) { if (i == 0 && m_materials.Count == 0) { // dummy - return MaterialFactory.DefaultCreateMaterialAsync(gltf, i, getTexture); + return MaterialFactory.DefaultCreateMaterialAsync(awaitCaller, gltf, i, getTexture); } - return MToonMaterialItem.CreateAsync(gltf, i, m_materials[i], getTexture); + return MToonMaterialItem.CreateAsync(awaitCaller, gltf, i, m_materials[i], getTexture); } } }