From 825aeab2cc07c5e48f277032a323a96fd978d556 Mon Sep 17 00:00:00 2001 From: Paul Du Bois Date: Mon, 3 Feb 2020 18:27:50 -0800 Subject: [PATCH] Bring gltf code in line with Tilt Brush 23 - Add ImportMaterialCollector to API (unused in TBT; only used in TB) - Rename PolyImportOptions -> GltfImportOptions - Remove unused ability to satisfy URIs with PolyFormat bundles - Remove unused GltfImportOptions "clientThrottledMainThread" - Remove #if'd out "gvrss" code This part may come back, if I bring over the blocks-specific materials and material lookup tables Change-Id: Id000b015f3c287ef28421f2f426d1330ef31cf17 --- .../TiltBrush/Scripts/Editor/Glb1Importer.cs | 6 +- .../TiltBrush/Scripts/Editor/Glb2Importer.cs | 6 +- .../Scripts/Editor/ModelImportSettings.cs | 2 +- .../TiltBrush/Scripts/Gltf/Gltf1Schema.cs | 13 +- .../TiltBrush/Scripts/Gltf/Gltf2Schema.cs | 10 +- ...yImportOptions.cs => GltfImportOptions.cs} | 33 ++--- ...ions.cs.meta => GltfImportOptions.cs.meta} | 0 .../Scripts/Gltf/GltfMaterialConverter.cs | 26 +--- .../Scripts/Gltf/GltfSchemaCommon.cs | 4 +- .../TiltBrush/Scripts/Gltf/IUriLoader.cs | 3 +- .../TiltBrush/Scripts/Gltf/ImportGltf.cs | 127 +++++++++++------- .../Scripts/Gltf/TemporaryPolyToolkitStubs.cs | 43 ------ .../Gltf/TemporaryPolyToolkitStubs.cs.meta | 11 -- .../TiltBrush/Scripts/SerializableGuid.cs | 12 +- .../Assets/TiltBrush/Scripts/TbtSettings.cs | 12 +- 15 files changed, 128 insertions(+), 180 deletions(-) rename UnitySDK/Assets/TiltBrush/Scripts/Gltf/{PolyImportOptions.cs => GltfImportOptions.cs} (63%) rename UnitySDK/Assets/TiltBrush/Scripts/Gltf/{PolyImportOptions.cs.meta => GltfImportOptions.cs.meta} (100%) delete mode 100644 UnitySDK/Assets/TiltBrush/Scripts/Gltf/TemporaryPolyToolkitStubs.cs delete mode 100644 UnitySDK/Assets/TiltBrush/Scripts/Gltf/TemporaryPolyToolkitStubs.cs.meta diff --git a/UnitySDK/Assets/TiltBrush/Scripts/Editor/Glb1Importer.cs b/UnitySDK/Assets/TiltBrush/Scripts/Editor/Glb1Importer.cs index 6d11a5c2..cd327696 100644 --- a/UnitySDK/Assets/TiltBrush/Scripts/Editor/Glb1Importer.cs +++ b/UnitySDK/Assets/TiltBrush/Scripts/Editor/Glb1Importer.cs @@ -32,8 +32,8 @@ public class Glb1Importer : ScriptedImporter { // import at queue offset = 0. const int kImportQueueOffset = 1; - private static readonly PolyImportOptions kOptions = new PolyImportOptions { - rescalingMode = PolyImportOptions.RescalingMode.CONVERT, + private static readonly GltfImportOptions kOptions = new GltfImportOptions { + rescalingMode = GltfImportOptions.RescalingMode.CONVERT, scaleFactor = 1, recenter = false, }; @@ -44,7 +44,7 @@ public override void OnImportAsset(AssetImportContext ctx) { ctx.assetPath, Path.GetDirectoryName(ctx.assetPath)); ImportGltf.GltfImportResult result = ImportGltf.Import( - GltfSchemaVersion.GLTF1, gltfStream, loader, kOptions); + GltfSchemaVersion.GLTF1, gltfStream, loader, null, kOptions); // The "identifier" param passed here is supposed to be: // - Unique to this asset diff --git a/UnitySDK/Assets/TiltBrush/Scripts/Editor/Glb2Importer.cs b/UnitySDK/Assets/TiltBrush/Scripts/Editor/Glb2Importer.cs index 9fcf7077..b315c4fe 100644 --- a/UnitySDK/Assets/TiltBrush/Scripts/Editor/Glb2Importer.cs +++ b/UnitySDK/Assets/TiltBrush/Scripts/Editor/Glb2Importer.cs @@ -32,8 +32,8 @@ public class Glb2Importer : ScriptedImporter { // import at queue offset = 0. const int kImportQueueOffset = 1; - private static readonly PolyImportOptions kOptions = new PolyImportOptions { - rescalingMode = PolyImportOptions.RescalingMode.CONVERT, + private static readonly GltfImportOptions kOptions = new GltfImportOptions { + rescalingMode = GltfImportOptions.RescalingMode.CONVERT, scaleFactor = 1, recenter = false, }; @@ -44,7 +44,7 @@ public override void OnImportAsset(AssetImportContext ctx) { ctx.assetPath, Path.GetDirectoryName(ctx.assetPath)); ImportGltf.GltfImportResult result = ImportGltf.Import( - GltfSchemaVersion.GLTF2, gltfStream, loader, kOptions); + GltfSchemaVersion.GLTF2, gltfStream, loader, null, kOptions); // The "identifier" param passed here is supposed to be: // - Unique to this asset diff --git a/UnitySDK/Assets/TiltBrush/Scripts/Editor/ModelImportSettings.cs b/UnitySDK/Assets/TiltBrush/Scripts/Editor/ModelImportSettings.cs index ab3933c3..82e5197b 100644 --- a/UnitySDK/Assets/TiltBrush/Scripts/Editor/ModelImportSettings.cs +++ b/UnitySDK/Assets/TiltBrush/Scripts/Editor/ModelImportSettings.cs @@ -24,7 +24,7 @@ namespace TiltBrushToolkit { public class ModelImportSettings : AssetPostprocessor { - private readonly Version kToolkitVersion = TbtSettings.Version; + private readonly Version kToolkitVersion = TbtSettings.TbtVersion; readonly Version kRequiredFbxExportVersion = new Version { major=10 }; public static bool sm_forceOldMeshNamingConvention = false; diff --git a/UnitySDK/Assets/TiltBrush/Scripts/Gltf/Gltf1Schema.cs b/UnitySDK/Assets/TiltBrush/Scripts/Gltf/Gltf1Schema.cs index 7eb38ea1..1ee5b1dc 100644 --- a/UnitySDK/Assets/TiltBrush/Scripts/Gltf/Gltf1Schema.cs +++ b/UnitySDK/Assets/TiltBrush/Scripts/Gltf/Gltf1Schema.cs @@ -86,7 +86,7 @@ protected override void Dispose(bool disposing) { } /// Map glTFid values (ie, string names) names to the objects they refer to - public override void Dereference(IUriLoader uriLoader = null, PolyFormat gltfFormat = null) { + public override void Dereference(IUriLoader uriLoader = null) { // "dereference" all the names scenePtr = scenes[scene]; foreach (var pair in buffers) { @@ -102,17 +102,8 @@ public override void Dereference(IUriLoader uriLoader = null, PolyFormat gltfFor Debug.Assert(buffer.uri != null); } buffer.data = uriLoader.Load(buffer.uri); - } else if (gltfFormat != null) { - // Runtime import case; the uris refer to resource files in the PolyFormat. - Debug.Assert(buffer.type == "arraybuffer"); - foreach (PolyFile resource in gltfFormat.resources) { - if (resource.relativePath == buffer.uri) { - buffer.data = new Reader(resource.contents); - break; - } - } - } } + } foreach (var pair in accessors) { pair.Value.gltfId = pair.Key; pair.Value.bufferViewPtr = bufferViews[pair.Value.bufferView]; diff --git a/UnitySDK/Assets/TiltBrush/Scripts/Gltf/Gltf2Schema.cs b/UnitySDK/Assets/TiltBrush/Scripts/Gltf/Gltf2Schema.cs index 6523e0fb..a3576cc7 100644 --- a/UnitySDK/Assets/TiltBrush/Scripts/Gltf/Gltf2Schema.cs +++ b/UnitySDK/Assets/TiltBrush/Scripts/Gltf/Gltf2Schema.cs @@ -87,7 +87,7 @@ protected override void Dispose(bool disposing) { } /// Map gltfIndex values (ie, int indices) names to the objects they refer to - public override void Dereference(IUriLoader uriLoader = null, PolyFormat gltfFormat = null) { + public override void Dereference(IUriLoader uriLoader = null) { // "dereference" all the indices scenePtr = scenes[scene]; for (int i = 0; i < buffers.Count; i++) { @@ -97,14 +97,6 @@ public override void Dereference(IUriLoader uriLoader = null, PolyFormat gltfFor // Only id 0 may lack a URI; this indicates that it is the binary chunk. Debug.Assert(! (i != 0 && buffer.uri == null)); buffer.data = uriLoader.Load(buffer.uri); - } else if (gltfFormat != null) { - // Runtime import case; the uris refer to resource files in the PolyFormat. - foreach (PolyFile resource in gltfFormat.resources) { - if (resource.relativePath == buffer.uri) { - buffer.data = new Reader(resource.contents); - break; - } - } } } for (int i = 0; i < accessors.Count; i++) { diff --git a/UnitySDK/Assets/TiltBrush/Scripts/Gltf/PolyImportOptions.cs b/UnitySDK/Assets/TiltBrush/Scripts/Gltf/GltfImportOptions.cs similarity index 63% rename from UnitySDK/Assets/TiltBrush/Scripts/Gltf/PolyImportOptions.cs rename to UnitySDK/Assets/TiltBrush/Scripts/Gltf/GltfImportOptions.cs index 40b14219..6561657c 100644 --- a/UnitySDK/Assets/TiltBrush/Scripts/Gltf/PolyImportOptions.cs +++ b/UnitySDK/Assets/TiltBrush/Scripts/Gltf/GltfImportOptions.cs @@ -14,23 +14,24 @@ using System; -using UnityEngine; - namespace TiltBrushToolkit { /// /// Options that indicate how to import a given asset. /// [Serializable] -[AutoStringifiable] -public struct PolyImportOptions { +public struct GltfImportOptions { public enum RescalingMode { - // Convert the object's units to scene units and optionally apply a scale as well - // (given by scaleFactor). + // Apply scaleFactor. CONVERT, - // Scale the object such that it fits a box of a particular size (desiredSize). + // Scale the object such that it fits a box of desiredSize, ignoring scaleFactor. FIT, } + /// + /// If not set, axis conventions default to the glTF 2.0 standard. + /// + public AxisConvention? axisConventionOverride; + /// /// What type of rescaling to perform. /// @@ -53,30 +54,16 @@ public enum RescalingMode { /// public bool recenter; - /// - /// If true, do not immediately perform heavy main thread operations (mesh import, texture creation, - /// etc) on import. Rather, an enumerator will be returned (mainThreadThrottler) in PolyImportResult - /// which you can enumerate to gradually create meshes and perform other heavy UI thread operations. - /// This option is useful for performance-sensitive applications that want to be in full control of - /// when Unity objects are created on the main thread. - /// - [HideInInspector] - public bool clientThrottledMainThread; - /// /// Returns a default set of import options. /// - public static PolyImportOptions Default() { - PolyImportOptions options = new PolyImportOptions(); + public static GltfImportOptions Default() { + GltfImportOptions options = new GltfImportOptions(); options.recenter = true; options.rescalingMode = RescalingMode.CONVERT; options.scaleFactor = 1.0f; options.desiredSize = 1.0f; return options; } - - public override string ToString() { - return AutoStringify.Stringify(this); - } } } diff --git a/UnitySDK/Assets/TiltBrush/Scripts/Gltf/PolyImportOptions.cs.meta b/UnitySDK/Assets/TiltBrush/Scripts/Gltf/GltfImportOptions.cs.meta similarity index 100% rename from UnitySDK/Assets/TiltBrush/Scripts/Gltf/PolyImportOptions.cs.meta rename to UnitySDK/Assets/TiltBrush/Scripts/Gltf/GltfImportOptions.cs.meta diff --git a/UnitySDK/Assets/TiltBrush/Scripts/Gltf/GltfMaterialConverter.cs b/UnitySDK/Assets/TiltBrush/Scripts/Gltf/GltfMaterialConverter.cs index be81b04c..924f8d4b 100644 --- a/UnitySDK/Assets/TiltBrush/Scripts/Gltf/GltfMaterialConverter.cs +++ b/UnitySDK/Assets/TiltBrush/Scripts/Gltf/GltfMaterialConverter.cs @@ -173,31 +173,13 @@ private static bool IsGlobalMaterial(GltfMaterialBase gltfMaterial) { /// The global material that corresponds to the given GLTF material, /// if found. If not found, null. private static Material LookUpGlobalMaterial(GltfMaterialBase gltfMaterial) { - // Is this a Blocks gvrss material? -#if false - if (gltfMaterial.TechniqueExtras != null) { - string surfaceShader = null; - gltfMaterial.TechniqueExtras.TryGetValue("gvrss", out surfaceShader); - - if (surfaceShader != null) { - // Blocks material. Look up the mapping in PtSettings. - Material material = PtSettings.Instance.LookupSurfaceShaderMaterial(surfaceShader); - if (material != null) { - return material; - } else { - Debug.LogWarningFormat("Unknown gvrss surface shader {0}", surfaceShader); - } - } - } -#endif - // Check if it's a Tilt Brush material. Guid guid = ParseGuidFromMaterial(gltfMaterial); if (guid != Guid.Empty) { // Tilt Brush global material. PBR materials will use unrecognized guids; // these will be handled by the caller. BrushDescriptor desc; - if (TiltBrushToolkit.TbtSettings.BrushManifest.BrushesByGuid.TryGetValue(guid, out desc)) { + if (TbtSettings.Instance.TryGetBrush(guid, out desc)) { return desc.Material; } } @@ -227,7 +209,7 @@ private static Material LookUpGlobalMaterial(GltfMaterialBase gltfMaterial) { Guid templateGuid = ParseGuidFromShader(gltfMat); BrushDescriptor desc; - if (!TiltBrushToolkit.TbtSettings.BrushManifest.BrushesByGuid.TryGetValue(templateGuid, out desc)) { + if (!TbtSettings.Instance.TryGetBrush(templateGuid, out desc)) { // If they are the same, there is no template/instance relationship. if (instanceGuid != templateGuid) { Debug.LogErrorFormat("Unexpected: cannot find template material {0} for {1}", @@ -445,7 +427,7 @@ public static BrushDescriptor LookupBrushDescriptor(GltfMaterialBase gltfMateria return null; } else { BrushDescriptor desc; - TiltBrushToolkit.TbtSettings.BrushManifest.BrushesByGuid.TryGetValue( + TbtSettings.Instance.TryGetBrush( guid, out desc); if (desc == null) { // Maybe it's templated from a pbr material; the template guid @@ -455,7 +437,7 @@ public static BrushDescriptor LookupBrushDescriptor(GltfMaterialBase gltfMateria return null; } Guid templateGuid = ParseGuidFromShader((Gltf1Material)gltfMaterial); - TiltBrushToolkit.TbtSettings.BrushManifest.BrushesByGuid.TryGetValue( + TbtSettings.Instance.TryGetBrush( templateGuid, out desc); } return desc; diff --git a/UnitySDK/Assets/TiltBrush/Scripts/Gltf/GltfSchemaCommon.cs b/UnitySDK/Assets/TiltBrush/Scripts/Gltf/GltfSchemaCommon.cs index 5566e978..bc390b4f 100644 --- a/UnitySDK/Assets/TiltBrush/Scripts/Gltf/GltfSchemaCommon.cs +++ b/UnitySDK/Assets/TiltBrush/Scripts/Gltf/GltfSchemaCommon.cs @@ -158,7 +158,7 @@ public abstract class GltfRootBase : IDisposable { public abstract IEnumerable Materials { get; } public abstract IEnumerable Meshes { get; } - public abstract void Dereference(IUriLoader uriLoader = null, PolyFormat gltfFormat = null); + public abstract void Dereference(IUriLoader uriLoader = null); // Disposable pattern, with Dispose(void) and Dispose(bool), as recommended by: // https://docs.microsoft.com/en-us/dotnet/api/system.idisposable @@ -214,6 +214,8 @@ public abstract class GltfPrimitiveBase { public abstract GltfMaterialBase MaterialPtr { get; } public abstract GltfAccessorBase IndicesPtr { get; } public abstract GltfAccessorBase GetAttributePtr(string attributeName); + // Rename attribute from original -> replacement. + // ie, attrs[replacement] = attrs.pop(original) public abstract void ReplaceAttribute(string original, string replacement); public abstract HashSet GetAttributeNames(); } diff --git a/UnitySDK/Assets/TiltBrush/Scripts/Gltf/IUriLoader.cs b/UnitySDK/Assets/TiltBrush/Scripts/Gltf/IUriLoader.cs index ad0a6f38..b31b70de 100644 --- a/UnitySDK/Assets/TiltBrush/Scripts/Gltf/IUriLoader.cs +++ b/UnitySDK/Assets/TiltBrush/Scripts/Gltf/IUriLoader.cs @@ -83,7 +83,7 @@ public interface IUriLoader { // ---------------------------------------------------------------------- - + public class Reader : IBufferReader { private byte[] data; @@ -113,6 +113,7 @@ public class BufferedStreamLoader : IUriLoader { private string uriBase; private int bufferSize; + /// glbPath is the .gltf or .glb file being read; or null. public BufferedStreamLoader(string glbPath, string uriBase, int bufferSize=4096) { this.glbPath = glbPath; this.uriBase = uriBase; diff --git a/UnitySDK/Assets/TiltBrush/Scripts/Gltf/ImportGltf.cs b/UnitySDK/Assets/TiltBrush/Scripts/Gltf/ImportGltf.cs index fb02e6dc..40045241 100644 --- a/UnitySDK/Assets/TiltBrush/Scripts/Gltf/ImportGltf.cs +++ b/UnitySDK/Assets/TiltBrush/Scripts/Gltf/ImportGltf.cs @@ -22,11 +22,25 @@ using Newtonsoft.Json; using UnityEngine; -using Semantic = TiltBrushToolkit.BrushDescriptor.Semantic; using Debug = UnityEngine.Debug; +using Semantic = TiltBrushToolkit.BrushDescriptor.Semantic; namespace TiltBrushToolkit { +public class Null { + protected Null() {} +} + +/// A callback that allows users to know when the import process has created a new material +public interface IImportMaterialCollector { + // Pass: + // unityMaterial - the template material, and the actual material used + // (which may be identical to the template material) + // gltfMaterial - the gltf node from which unityMaterial was generated + void Add(GltfMaterialConverter.UnityMaterial unityMaterial, + GltfMaterialBase gltfMaterial); +} + public static class ImportGltf { /// /// Minimum sane bounding box size to perform automatic fitting to a given size. @@ -58,6 +72,7 @@ public class GltfImportResult { public List meshes; public List materials; public List textures; + public IImportMaterialCollector materialCollector = null; } /// State data used by the import process. @@ -99,15 +114,17 @@ public void Dispose() { /// The glTF format version to use. /// A stream containing the contents of the .gltf file. Ownership of the stream is transferred; it will be closed after the import. /// For fetching relative URIs referenced by the .gltf file. + /// May be null if you don't need it. /// The options to import the model with. /// /// public static GltfImportResult Import( GltfSchemaVersion gltfVersion, TextReader gltfStream, IUriLoader uriLoader, - PolyImportOptions options) { + IImportMaterialCollector materialCollector, + GltfImportOptions options) { using (var state = BeginImport(gltfVersion, gltfStream, uriLoader, options)) { - IEnumerable meshCreator; - GltfImportResult result = EndImport(state, uriLoader, out meshCreator); + IEnumerable meshCreator; + GltfImportResult result = EndImport(state, uriLoader, materialCollector, out meshCreator); foreach (var unused in meshCreator) { // create meshes! } @@ -129,7 +146,7 @@ private static GltfRootBase DeserializeGltfRoot(GltfSchemaVersion gltfVersion, J return gltf1Root; } case GltfSchemaVersion.GLTF2: - var gltf2Root= kSerializer.Deserialize(reader); + var gltf2Root = kSerializer.Deserialize(reader); if (gltf2Root == null || gltf2Root.nodes == null) { throw new Exception("Failed to parse GLTF2. File is empty or in the wrong format."); } @@ -139,22 +156,45 @@ private static GltfRootBase DeserializeGltfRoot(GltfSchemaVersion gltfVersion, J } } - private static void SanityCheckImportOptions(PolyImportOptions options) { - if (options.rescalingMode == PolyImportOptions.RescalingMode.CONVERT && + private static void SanityCheckImportOptions(GltfImportOptions options) { + if (options.rescalingMode == GltfImportOptions.RescalingMode.CONVERT && options.scaleFactor == 0.0f) { // If scaleFactor is exactly zero (not just close), it's PROBABLY because of user error, - // because this is what happens when you do "new PolyImportOptions()" and forget to set - // scaleFactor. PolyImportOptions is a struct so we can't have a default value. - throw new Exception("scaleFactor must be != 0 for PolyImportOptions CONVERT mode. " + + // because this is what happens when you do "new GltfImportOptions()" and forget to set + // scaleFactor. GltfImportOptions is a struct so we can't have a default value. + throw new Exception("scaleFactor must be != 0 for GltfImportOptions CONVERT mode. " + "Did you forget to set scaleFactor?"); - } else if (options.rescalingMode == PolyImportOptions.RescalingMode.FIT && + } else if (options.rescalingMode == GltfImportOptions.RescalingMode.FIT && options.desiredSize <= 0.0f) { - throw new Exception("desiredSize must be > 0 for PolyImportOptions FIT mode. " + + throw new Exception("desiredSize must be > 0 for GltfImportOptions FIT mode. " + "Did you forget to set desiredSize?"); } } + private static void CheckCompatibility( + GltfRootBase root, string versionKey, Version currentVersion) { + var extras = root.asset.extras; + if (extras == null) { return; } + + string requiredVersion; + extras.TryGetValue(versionKey, out requiredVersion); + if (requiredVersion != null) { + Match match = Regex.Match(requiredVersion, @"^([0-9]+)\.([0-9]+)"); + if (match.Success) { + var required = new Version { + major = int.Parse(match.Groups[1].Value), + minor = int.Parse(match.Groups[2].Value) + }; + if (required > currentVersion) { + Debug.LogWarningFormat( + "This file specifies {0} {1}; you are currently using {2}", + versionKey, required, currentVersion); + } + } + } + } + /// /// The portion of that can be /// performed off the main thread. The parameters are the same as for Import. @@ -162,12 +202,15 @@ private static void SanityCheckImportOptions(PolyImportOptions options) { /// An object which should be passed to and then disposed public static ImportState BeginImport( GltfSchemaVersion gltfVersion, TextReader stream, IUriLoader uriLoader, - PolyImportOptions options) { + GltfImportOptions options) { + if (stream == null) { throw new ArgumentNullException("stream"); } + if (uriLoader == null) { throw new ArgumentNullException("uriLoader"); } SanityCheckImportOptions(options); using (var reader = new JsonTextReader(stream)) { var root = DeserializeGltfRoot(gltfVersion, reader); + if (root == null) { throw new NullReferenceException("root"); } root.Dereference(uriLoader); // Convert attribute names to the ones we expect. @@ -195,28 +238,11 @@ public static ImportState BeginImport( } } - // Allow the glTF to define the limit of PT's data forward-compatibility - if (root.asset.extras != null) { - string requiredPtVersion; - root.asset.extras.TryGetValue("requiredTiltBrushToolkitVersion", out requiredPtVersion); - if (requiredPtVersion != null) { - Match match = Regex.Match(requiredPtVersion, @"^([0-9]+)\.([0-9]+)"); - if (match.Success) { - var required = new Version { - major = int.Parse(match.Groups[1].Value), - minor = int.Parse(match.Groups[2].Value) - }; - if (required > TbtSettings.Version) { - Debug.LogWarningFormat( - "This file requires Tilt Brush Toolkit {0}; you are currently using {1}", - required, TbtSettings.Version); - } - } - } - } + // Allow the glTF to define the limit of our data forward-compatibility + CheckCompatibility(root, "requiredTiltBrushToolkitVersion", TbtSettings.TbtVersion); } - var state = new ImportState(AxisConvention.kGltf2) { + var state = new ImportState(options.axisConventionOverride ?? AxisConvention.kGltf2) { root = root, desiredScene = root.ScenePtr, }; @@ -260,10 +286,10 @@ public static ImportState BeginImport( // the object's geometry to keep within Unity's modelview scale limits, and as a // result have to compensate for the scale at the top node. static void ComputeScaleFactor( - PolyImportOptions options, Bounds boundsInGltfSpace, + GltfImportOptions options, Bounds boundsInGltfSpace, out float directScaleFactor, out float nodeScaleFactor) { switch (options.rescalingMode) { - case PolyImportOptions.RescalingMode.CONVERT: + case GltfImportOptions.RescalingMode.CONVERT: directScaleFactor = options.scaleFactor; nodeScaleFactor = 1; float requiredShrink; @@ -280,7 +306,7 @@ static void ComputeScaleFactor( } } return; - case PolyImportOptions.RescalingMode.FIT: + case GltfImportOptions.RescalingMode.FIT: // User wants a specific size, so derive it from the bounding box. if (!ComputeScaleFactorToFit(boundsInGltfSpace, options.desiredSize, out directScaleFactor)) { Debug.LogWarningFormat("Could not automatically resize object; object is too small or empty."); @@ -384,20 +410,25 @@ static bool ComputeScaleFactorToFit(Bounds bounds, float desiredSize, out float /// /// Returned by BeginImport /// For fetching relative URIs referenced by the .gltf file. + /// May be null if you don't need it /// out reference to an enumerable that should be enumerated /// to create the unity meshes. static public GltfImportResult EndImport( - ImportState state, IUriLoader uriLoader, out IEnumerable meshCreator) { + ImportState state, + IUriLoader uriLoader, + IImportMaterialCollector materialCollector, + out IEnumerable meshCreator) { var result = new GltfImportResult { - root = new GameObject("PolyImport"), + root = new GameObject("GltfImport"), meshes = new List(), + materialCollector = materialCollector }; meshCreator = CreateGameObjectsFromNodes(state, result, uriLoader); return result; } - static IEnumerable CreateGameObjectsFromNodes( + static IEnumerable CreateGameObjectsFromNodes( ImportState state, GltfImportResult result, IUriLoader uriLoader) { var loaded = new List(); foreach (var unused in GltfMaterialConverter.LoadTexturesCoroutine( @@ -490,7 +521,13 @@ static IEnumerable CreateGameObjectsFromMesh( // https://github.com/KhronosGroup/glTF/issues/1065 for (int iP = 0; iP < mesh.PrimitiveCount; ++iP) { GltfPrimitiveBase prim = mesh.GetPrimitiveAt(iP); - GltfMaterialConverter.UnityMaterial? unityMaterial = matConverter.GetMaterial(prim.MaterialPtr); + GltfMaterialConverter.UnityMaterial? unityMaterial = + matConverter.GetMaterial(prim.MaterialPtr); + if (result.materialCollector != null && unityMaterial != null) { + Debug.Assert(unityMaterial.Value.material != null); + // Generate IExportableMaterial for later exports. + result.materialCollector.Add(unityMaterial.Value, prim.MaterialPtr); + } if (prim.precursorMeshes == null) { continue; @@ -730,7 +767,8 @@ static void ChangeBasisAndApplyScale( } // Annotates GltfPrimitive with materials, precursorMeshes - static List CreateMeshPrecursorsFromPrimitive(ImportState state, GltfPrimitiveBase prim) { + static List CreateMeshPrecursorsFromPrimitive( + ImportState state, GltfPrimitiveBase prim) { if (prim.mode != GltfPrimitiveBase.Mode.TRIANGLES) { Debug.LogWarningFormat("Cannot create mesh from {0}", prim.mode); return null; @@ -774,7 +812,6 @@ static List CreateMeshPrecursorsFromPrimitive(ImportState state, } } - List meshes = new List(); // Tilt Brush particle meshes are sensitive to being broken up. @@ -797,8 +834,7 @@ static List CreateMeshPrecursorsFromPrimitive(ImportState state, // count. In these cases, be lenient and ignore the missing data. if (attribRange.min >= accessor.count) { // No data at all for this accessor (entirely out of range). - // This is a verbose log, not a warning, because it's accepted as "correct". - PtDebug.LogVerboseFormat("Attribute {0} has no data: wanted range {1}, count was {2}", + Debug.LogWarningFormat("Attribute {0} has no data: wanted range {1}, count was {2}", semantic, attribRange, accessor.count); // Ignore this attribute. continue; @@ -1013,7 +1049,8 @@ private static void FixInvalidNormals(MeshPrecursor mesh) { // Returns a Semantic which tells us how to manipulate the uv to convert it // from glTF conventions to Unity conventions. - static Semantic GetTexcoordSemantic(ImportState state, GltfMaterialBase material, int uvChannel) { + static Semantic GetTexcoordSemantic( + ImportState state, GltfMaterialBase material, int uvChannel) { // GL and Unity use the convention "texture origin is lower-left" // glTF, DX, Metal, and modern APIs use the convention "texture origin is upper-left" // We want to match the logic used by the exporter which generated this gltf, down to its bugs. diff --git a/UnitySDK/Assets/TiltBrush/Scripts/Gltf/TemporaryPolyToolkitStubs.cs b/UnitySDK/Assets/TiltBrush/Scripts/Gltf/TemporaryPolyToolkitStubs.cs deleted file mode 100644 index 614606ac..00000000 --- a/UnitySDK/Assets/TiltBrush/Scripts/Gltf/TemporaryPolyToolkitStubs.cs +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright 2019 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// https://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -using System; -using System.Collections.Generic; - -namespace TiltBrushToolkit { - -public class PolyFormat { - public List resources { get { return null; } } -} - -public class PolyFile { - public string relativePath { get { return null; } } - public byte[] contents { get { return null; } } -} - -public static class PtDebug { - public static void LogVerboseFormat(params object[] args) {} -} - -public class AutoStringifiable : Attribute {} - -public class AutoStringify : Attribute { - public static string Stringify(object o) { return null; } -} - -public struct LengthWithUnit { - public float ToMeters() { return 0; } -} - -} diff --git a/UnitySDK/Assets/TiltBrush/Scripts/Gltf/TemporaryPolyToolkitStubs.cs.meta b/UnitySDK/Assets/TiltBrush/Scripts/Gltf/TemporaryPolyToolkitStubs.cs.meta deleted file mode 100644 index 4761b454..00000000 --- a/UnitySDK/Assets/TiltBrush/Scripts/Gltf/TemporaryPolyToolkitStubs.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 548439c8a02f77540b3f203ecbdc0fc9 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnitySDK/Assets/TiltBrush/Scripts/SerializableGuid.cs b/UnitySDK/Assets/TiltBrush/Scripts/SerializableGuid.cs index 5e29b105..0405c8ee 100644 --- a/UnitySDK/Assets/TiltBrush/Scripts/SerializableGuid.cs +++ b/UnitySDK/Assets/TiltBrush/Scripts/SerializableGuid.cs @@ -12,6 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. +using System; using UnityEngine; #if UNITY_EDITOR using UnityEditor; @@ -52,7 +53,7 @@ public override void OnGUI(Rect position, SerializedProperty property, GUIConten /// Adds the expense of conversions to/from native System.Guid, /// but enables Unity serialization. [System.Serializable] -public struct SerializableGuid { +public struct SerializableGuid : IFormattable { [SerializeField] private string m_storage; @@ -61,7 +62,10 @@ public static implicit operator SerializableGuid(System.Guid rhs) { } public static implicit operator System.Guid(SerializableGuid rhs) { - if (rhs.m_storage == null) return System.Guid.Empty; + if (rhs.m_storage == null) { + return System.Guid.Empty; + } + try { return new System.Guid(rhs.m_storage); } catch (System.FormatException) { @@ -73,9 +77,9 @@ public override string ToString() { return ToString("D"); } - public string ToString(string format) { + public string ToString(string format, IFormatProvider provider=null) { return ((System.Guid)this).ToString(format); } } -} // namespace TiltBrush +} // namespace TiltBrushToolkit diff --git a/UnitySDK/Assets/TiltBrush/Scripts/TbtSettings.cs b/UnitySDK/Assets/TiltBrush/Scripts/TbtSettings.cs index 1117da3a..5e296440 100644 --- a/UnitySDK/Assets/TiltBrush/Scripts/TbtSettings.cs +++ b/UnitySDK/Assets/TiltBrush/Scripts/TbtSettings.cs @@ -13,6 +13,7 @@ // limitations under the License. using System; + using UnityEngine; namespace TiltBrushToolkit { @@ -34,12 +35,12 @@ public static TbtSettings Instance { } } - public static Version Version { - get { return new Version { major = 21, minor = 0 }; } + public static Version TbtVersion { + get { return new Version { major = 23, minor = 0 }; } } public static BrushManifest BrushManifest { - get { return Instance.m_BrushManifest; } + get { return sm_Instance.m_BrushManifest; } } [SerializeField] private BrushManifest m_BrushManifest = null; @@ -50,6 +51,11 @@ public static BrushManifest BrushManifest { // This is the same material used by the BrushDescriptor "PbrTransparentTemplate" public Material m_BasePbrBlendDoubleSidedMaterial; public Material m_BasePbrBlendSingleSidedMaterial; + + /// null if not found + public bool TryGetBrush(Guid guid, out BrushDescriptor desc) { + return m_BrushManifest.BrushesByGuid.TryGetValue(guid, out desc); + } } }