Recently, I have been developing an SDK for Unity character images. The goal is that the SDK can dynamically download the latest models of characters and clothing without having to be built into the SDK in advance.
At the beginning, the solution I plan to use is the traditional and mature Addressables way to package bundles, but the division of bundles is a problem, and this method needs to import the model into unity every time, then release the package, and then update the catalog. The whole process is relatively tedious.
So I was wondering if I could load FBX and textures directly from remote, and then load them directly using FBX, so that the whole release process would be much simpler.
After some searching, he found the TriLib repository, which was very convenient for him to load models remotely. However, there were also some problems. In order to locate these problems, I specially read the source code.
Usage
In fact, the usage of TriLib is very simple. It does not have the ability to open many configurations in total. After you import it, it is very clear to take a look at its example, but it is still simply displayed here
using TriLibCore.General; using UnityEngine; namespaceTriLibCore.Samples { ///<summary> /// Represents a sample that loads a compressed (Zipped) Model. ///</summary> publicclassLoadModelFromURLSample : MonoBehaviour { publicstring modelUrl; ///<summary> /// Creates the AssetLoaderOptions instance, configures the Web Request, and downloads the Model. ///</summary> ///<remarks> /// You can create the AssetLoaderOptions by right clicking on the Assets Explorer and selecting "TriLib->Create->AssetLoaderOptions->Pre-Built AssetLoaderOptions". ///</remarks> /// privatevoidStart() { var assetLoaderOptions = AssetLoader.CreateDefaultLoaderOptions(); var webRequest = AssetDownloader.CreateWebRequest(modelUrl); AssetDownloader.LoadModelFromUri(webRequest, OnLoad, OnMaterialsLoad, OnProgress, OnError, null, assetLoaderOptions); }
///<summary> /// Called when any error occurs. ///</summary> ///<param name="obj">The contextualized error, containing the original exception and the context passed to the method where the error was thrown.</param> privatevoidOnError(IContextualizedError obj) { Debug.LogError($"An error ocurred while loading your Model: {obj.GetInnerException()}"); }
///<summary> /// Called when the Model loading progress changes. ///</summary> ///<param name="assetLoaderContext">The context used to load the Model.</param> ///<param name="progress">The loading progress.</param> privatevoidOnProgress(AssetLoaderContext assetLoaderContext, float progress) { Debug.Log($"Loading Model. Progress: {progress:P}"); }
///<summary> /// Called when the Model (including Textures and Materials) has been fully loaded, or after any error occurs. ///</summary> ///<remarks>The loaded GameObject is available on the assetLoaderContext.RootGameObject field.</remarks> ///<param name="assetLoaderContext">The context used to load the Model.</param> privatevoidOnMaterialsLoad(AssetLoaderContext assetLoaderContext) { Debug.Log("Materials loaded. Model fully loaded."); }
///<summary> /// Called when the Model Meshes and hierarchy are loaded. ///</summary> ///<remarks>The loaded GameObject is available on the assetLoaderContext.RootGameObject field.</remarks> ///<param name="assetLoaderContext">The context used to load the Model.</param> privatevoidOnLoad(AssetLoaderContext assetLoaderContext) { Debug.Log("Model loaded. Loading materials."); } } }
This code is very simple. It should be noted that the content downloaded from the corresponding download link needs to be a zip file, which contains the model and the materials, textures, etc. referenced by the model.
Use attention
Does the above code look simple, but you may find it useless? I encountered two problems
Unable to find the corresponding MaterailMapper (v2.0.6)
If there is a waring in your console, which probably means that MaterialMapper cannot be found, don’t ignore this error, because if you can’t find this thing, the result is that the model cannot be loaded correctly.
I have this problem because my project is part of the URP rendering pipeline.
Then the code will determine whether you are a normal rendering pipeline, URP or HDRP, and then find a suitable Material to render the model based on this.
So this thing is judged to be successful. The file name used by the URP Settings you configured must be “UniversalRP”, and the URP generated by default is called “UniversalRenderPipeline”, and then he can’t recognize it, so he can’t add materials to your FBX
The material is wrong, and there is one more material (v2.0.6)
So far, the author still encountered a problem, that is, in addition to the name of the material, the other is wrong, not only the property is wrong, but also one more material. For this reason, the author specially studied the source code and found that this thing is intentional.
publicstatic AssetLoaderOptions CreateDefaultLoaderOptions(bool generateAssets = false) { var assetLoaderOptions = ScriptableObject.CreateInstance<AssetLoaderOptions>(); ByNameRootBoneMapper byNameRootBoneMapper; #if UNITY_EDITOR if (generateAssets) { byNameRootBoneMapper = (ByNameRootBoneMapper)LoadOrCreateScriptableObject("ByNameRootBoneMapper", "RootBone"); } else { byNameRootBoneMapper = ScriptableObject.CreateInstance<ByNameRootBoneMapper>(); } #else byNameRootBoneMapper = ScriptableObject.CreateInstance<ByNameRootBoneMapper>(); #endif byNameRootBoneMapper.name = "ByNameRootBoneMapper"; assetLoaderOptions.RootBoneMapper = byNameRootBoneMapper; if (MaterialMapper.RegisteredMappers.Count 0) { Debug.LogWarning("Please add at least one MaterialMapper name to the MaterialMapper.RegisteredMappers static field to create the right MaterialMapper for the Render Pipeline you are using."); } else { var materialMappers = new List<MaterialMapper>(); foreach (var materialMapperName in MaterialMapper.RegisteredMappers) { if (materialMapperName null) { continue; } MaterialMapper materialMapper; #if UNITY_EDITOR if (generateAssets) { materialMapper = (MaterialMapper)LoadOrCreateScriptableObject(materialMapperName, "Material"); } else { materialMapper = (MaterialMapper)ScriptableObject.CreateInstance(materialMapperName); } #else materialMapper = ScriptableObject.CreateInstance(materialMapperName) as MaterialMapper; #endif if (materialMapper != null) { materialMapper.name = materialMapperName; if (materialMapper.IsCompatible(null)) { materialMappers.Add(materialMapper); assetLoaderOptions.FixedAllocations.Add(materialMapper); } else { #if UNITY_EDITOR var assetPath = AssetDatabase.GetAssetPath(materialMapper); if (assetPath null) { Object.DestroyImmediate(materialMapper); } #else Object.Destroy(materialMapper); #endif } } } if (materialMappers.Count 0) { Debug.LogWarning("TriLib could not find any suitable MaterialMapper on the project."); } else { assetLoaderOptions.MaterialMappers = materialMappers.ToArray(); } } //These two animation clip mappers are used to convert legacy to humanoid animations and add a simple generic animation playback component to the model, which will be disabled by default. LegacyToHumanoidAnimationClipMapper legacyToHumanoidAnimationClipMapper; SimpleAnimationPlayerAnimationClipMapper simpleAnimationPlayerAnimationClipMapper; #if UNITY_EDITOR if (generateAssets) { legacyToHumanoidAnimationClipMapper = (LegacyToHumanoidAnimationClipMapper)LoadOrCreateScriptableObject("LegacyToHumanoidAnimationClipMapper", "AnimationClip"); simpleAnimationPlayerAnimationClipMapper = (SimpleAnimationPlayerAnimationClipMapper)LoadOrCreateScriptableObject("SimpleAnimationPlayerAnimationClipMapper", "AnimationClip"); } else { legacyToHumanoidAnimationClipMapper = ScriptableObject.CreateInstance<LegacyToHumanoidAnimationClipMapper>(); simpleAnimationPlayerAnimationClipMapper = ScriptableObject.CreateInstance<SimpleAnimationPlayerAnimationClipMapper>(); } #else legacyToHumanoidAnimationClipMapper = ScriptableObject.CreateInstance<LegacyToHumanoidAnimationClipMapper>(); simpleAnimationPlayerAnimationClipMapper = ScriptableObject.CreateInstance<SimpleAnimationPlayerAnimationClipMapper>(); #endif legacyToHumanoidAnimationClipMapper.name = "LegacyToHumanoidAnimationClipMapper"; simpleAnimationPlayerAnimationClipMapper.name = "SimpleAnimationPlayerAnimationClipMapper"; assetLoaderOptions.AnimationClipMappers = new AnimationClipMapper[] { legacyToHumanoidAnimationClipMapper, simpleAnimationPlayerAnimationClipMapper }; assetLoaderOptions.FixedAllocations.Add(assetLoaderOptions); assetLoaderOptions.FixedAllocations.Add(legacyToHumanoidAnimationClipMapper); assetLoaderOptions.FixedAllocations.Add(simpleAnimationPlayerAnimationClipMapper); return assetLoaderOptions; }
This code first does three main things, namely to find the appropriate’RootBoneMapper ‘,’ MaterialMapper ‘,’ AnimationPlayerAninamtionClipMapper '.
We take MaterialMapper as an example. When the model imported by this tool is not imported into Material, then the tool is needed to help create a Material. So how does Trilib determine what Material to use? This is what was said in the question just now.
For example, if we use a URP, the final MaterialMapper selected is’UniversalRPMaterialMapper '.
The corresponding presets in the code can be seen directly in the folder.
Each Mapper first constructs the function and adds its own to’MaterialMapper. RegisteredMappers’. Only in this variable will it enter the list to be selected
And each Mapper exposes only two methods, one is’IsCompatible ‘, that is, using the variables involved in the first question, and the other is’Map’. In this function, all private functions will be called in sequence., each function checks a property in the FBX file, and then sets the property of the final material used.
Finally, the’BuildMaterial 'method will be called. The definition of this method is very simple.
private Material InstantiateSuitableMaterial(MaterialMapperContext materialMapperContext) { Material material; if (!materialMapperContext.Context.LoadedMaterials.TryGetValue(materialMapperContext.Material, out material)) { bool flag = materialMapperContext.Context.Options.UseAlphaMaterials && materialMapperContext.VirtualMaterial.HasAlpha && !this.ForceStandardMaterial; if (materialMapperContext.Material.MaterialShadingSetup MaterialShadingSetup.Specular) { if ((UnityEngine.Object) this.SpecularAlphaMaterialPreset != (UnityEngine.Object) null & flag) material = UnityEngine.Object.Instantiate<Material>(this.SpecularAlphaMaterialPreset); elseif ((UnityEngine.Object) this.SpecularMaterialPreset != (UnityEngine.Object) null) material = UnityEngine.Object.Instantiate<Material>(this.SpecularMaterialPreset); } if ((UnityEngine.Object) material (UnityEngine.Object) null) material = UnityEngine.Object.Instantiate<Material>(flag ? this.AlphaMaterialPreset : this.MaterialPreset); MaterialMapper.ApplyMaterialProperties(materialMapperContext, material); materialMapperContext.Context.LoadedMaterials.Add(materialMapperContext.Material, material); materialMapperContext.Context.Allocations.Add((UnityEngine.Object) material); } return material; }
If when we load FBX, we also load material, that is, it can be directly obtained from the’LoadedMaterials’ variable, then use it directly. If not, choose a material from the preset.
This is how the first material in our final model came about. As for when this method is called, we will talk about it below.
CreateWebRequest(modelUrl);
There is nothing to say about this method, it is to create UnityWebRequest.
Here is mainly to open a Thread to call LoadModel and ProcessRootModel respectively
LoadModel content is relatively easy to understand, is to read the FBX content, but this step reads out a lot of properties have a great impact on the subsequent processing, but also why I have a second material, and determines my second material is How to choose
The last three lines add sharedMaterilas to m, then add a created Material, and finally assign it together to Render.materials.
Summary and solution
The simple call flow of the two materials can be summarized as follows:
CreateDefaultLoaderOptions的时候选择了一个MaterialMapper
After the model is downloaded successfully, import it through the LoadModel method
After LoadModel succeeds, ProcessRootModel calls ProcessModel to process the properties of the Model, and ProcessTexture is used to process the texture
ProcessTextures最终会调用ProcessMaterial
ProcessMaterial will first call the Map method of the MaterialMapper selected in the first step to create a material, and then call the ApplyMaterialToRenderer of the MaterialMapper to create another material. The materials created in these two steps are selected according to one of the templates set in advance, and the selection is based on the configuration that comes with the LoadModel import.
The solution is to set the useAlpha property to false (the default is true) when creating assetOptions in the first step.
loadFbxFromZipFile丢失贴图(v2.1.6)
When you successfully import fbx, you will find that there may be no textures in your material. At this time, you need to check whether the texture name in the zip package is correct, that is, what is the texture name specified in your fbx, and what is your actual texture name. What is the name, trilib is mapped by file name.
IsReadable for textures is false (v2.1.6)
After upgrading to version 2.1.6, the textures in the imported material of trilib cannot be read, that is, ‘Read/Write Enable’ is not checked.
This can be seen on the official doc that this is intentional, and there is no option to modify this configuration, so we can only modify its underlying code.
In the end, I chose to change the’ApplyDiffuseMapTexture 'method in MaterialMapper, because my project is a URP project, so I modified UniversalUniversalRPMaterialMapper
1 2 3 4 5 6 7 8 9 10 11 12 13
privatevoidApplyDiffuseMapTexture(TextureLoadingContext textureLoadingContext) { if (textureLoadingContext.UnityTexture != null) { Texture2D unityTexture = new Texture2D(textureLoadingContext.UnityTexture.width, textureLoadingContext.UnityTexture.height, textureLoadingContext.UnityTexture.graphicsFormat, textureLoadingContext.UnityTexture.mipmapCount, TextureCreationFlags.None);