Use and source code analysis of TriLib remote loading FBX under Unity

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
using TriLibCore.General;
using UnityEngine;
namespace TriLibCore.Samples
{
/// <summary>
/// Represents a sample that loads a compressed (Zipped) Model.
/// </summary>
public class LoadModelFromURLSample : MonoBehaviour
{
public string 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>
///
private void Start()
{
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>
private void OnError(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>
private void OnProgress(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>
private void OnMaterialsLoad(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>
private void OnLoad(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.

The judgment logic of the URP is as follows:

1
2
3
4
5
6
7
public override bool IsCompatible(MaterialMapperContext materialMapperContext)
{
return GraphicsSettingsUtils.IsUsingUniversalPipeline;
}

public static bool IsUsingUniversalPipeline => GraphicsSettings.renderPipelineAsset != null && GraphicsSettings.renderPipelineAsset.name.StartsWith("UniversalRP");

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.

Let me first explain why this is:

CreateDefaultLoaderOptions

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
public static 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 code is as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
public class UniversalRPMaterialMapper : MaterialMapper
{
static UniversalRPMaterialMapper()
{
AddToRegisteredMappers();
}

[RuntimeInitializeOnLoadMethod]
private static void AddToRegisteredMappers()
{
if (RegisteredMappers.Contains("UniversalRPMaterialMapper"))
{
return;
}
RegisteredMappers.Add("UniversalRPMaterialMapper");
}

public override Material MaterialPreset => Resources.Load<Material>("Materials/UniversalRP/TriLibUniversalRP");

public override Material AlphaMaterialPreset => Resources.Load<Material>("Materials/UniversalRP/TriLibUniversalRPAlphaCutout");

public override Material AlphaMaterialPreset2 => Resources.Load<Material>("Materials/UniversalRP/TriLibUniversalRPAlpha");

public override Material SpecularMaterialPreset => Resources.Load<Material>("Materials/UniversalRP/TriLibUniversalRPSpecular");

public override Material SpecularAlphaMaterialPreset => Resources.Load<Material>("Materials/UniversalRP/TriLibUniversalRPAlphaCutoutSpecular");

public override Material SpecularAlphaMaterialPreset2 => Resources.Load<Material>("Materials/UniversalRP/TriLibUniversalRPAlphaSpecular");

public override Material LoadingMaterial => Resources.Load<Material>("Materials/UniversalRP/TriLibUniversalRPLoading");

///<inheritdoc />
public override bool IsCompatible(MaterialMapperContext materialMapperContext)
{
return GraphicsSettingsUtils.IsUsingUniversalPipeline;
}

///<inheritdoc />
public override void Map(MaterialMapperContext materialMapperContext)
{
materialMapperContext.VirtualMaterial = new VirtualMaterial();
CheckDiffuseMapTexture(materialMapperContext);
}

private void CheckDiffuseMapTexture(MaterialMapperContext materialMapperContext)
{
var diffuseTexturePropertyName = materialMapperContext.Material.GetGenericPropertyName(GenericMaterialProperty.DiffuseTexture);
if (materialMapperContext.Material.HasProperty(diffuseTexturePropertyName))
{
LoadTexture(materialMapperContext, TextureType.Diffuse, materialMapperContext.Material.GetTextureValue(diffuseTexturePropertyName), ApplyDiffuseMapTexture);
}
else
{
ApplyDiffuseMapTexture(materialMapperContext, TextureType.Diffuse, null);
}
}

private void ApplyDiffuseMapTexture(MaterialMapperContext materialMapperContext, TextureType textureType, Texture texture)
{
materialMapperContext.VirtualMaterial.SetProperty("_BaseMap", texture);
CheckGlossinessValue(materialMapperContext);
}

private void CheckGlossinessValue(MaterialMapperContext materialMapperContext)
{
var value = materialMapperContext.Material.GetGenericPropertyValueMultiplied(GenericMaterialProperty.Glossiness, materialMapperContext.Material.GetGenericFloatValue(GenericMaterialProperty.Glossiness));
materialMapperContext.VirtualMaterial.SetProperty("_Glossiness", value);
CheckMetallicValue(materialMapperContext);
}

private void CheckMetallicValue(MaterialMapperContext materialMapperContext)
{
var value = materialMapperContext.Material.GetGenericFloatValue(GenericMaterialProperty.Metallic);
materialMapperContext.VirtualMaterial.SetProperty("_Metallic", value);
CheckEmissionMapTexture(materialMapperContext);
}

private void CheckEmissionMapTexture(MaterialMapperContext materialMapperContext)
{
var emissionTexturePropertyName = materialMapperContext.Material.GetGenericPropertyName(GenericMaterialProperty.EmissionTexture);
if (materialMapperContext.Material.HasProperty(emissionTexturePropertyName))
{
LoadTexture(materialMapperContext, TextureType.Emission, materialMapperContext.Material.GetTextureValue(emissionTexturePropertyName), ApplyEmissionMapTexture);
}
else
{
ApplyEmissionMapTexture(materialMapperContext, TextureType.Emission, null);
}
}

private void ApplyEmissionMapTexture(MaterialMapperContext materialMapperContext, TextureType textureType, Texture texture)
{
materialMapperContext.VirtualMaterial.SetProperty("_EmissionMap", texture);
if (texture)
{
materialMapperContext.VirtualMaterial.EnableKeyword("_EMISSION");
materialMapperContext.VirtualMaterial.GlobalIlluminationFlags = MaterialGlobalIlluminationFlags.RealtimeEmissive;
}
else
{
materialMapperContext.VirtualMaterial.DisableKeyword("_EMISSION");
materialMapperContext.VirtualMaterial.GlobalIlluminationFlags = MaterialGlobalIlluminationFlags.EmissiveIsBlack;
}
CheckNormalMapTexture(materialMapperContext);
}

private void CheckNormalMapTexture(MaterialMapperContext materialMapperContext)
{
var normalMapTexturePropertyName = materialMapperContext.Material.GetGenericPropertyName(GenericMaterialProperty.NormalTexture);
if (materialMapperContext.Material.HasProperty(normalMapTexturePropertyName))
{
LoadTexture(materialMapperContext, TextureType.NormalMap, materialMapperContext.Material.GetTextureValue(normalMapTexturePropertyName), ApplyNormalMapTexture);
}
else
{
ApplyNormalMapTexture(materialMapperContext, TextureType.NormalMap, null);
}
}

private void ApplyNormalMapTexture(MaterialMapperContext materialMapperContext, TextureType textureType, Texture texture)
{
materialMapperContext.VirtualMaterial.SetProperty("_BumpMap", texture);
if (texture != null)
{
materialMapperContext.VirtualMaterial.EnableKeyword("_NORMALMAP");
materialMapperContext.VirtualMaterial.SetProperty("_NormalScale", materialMapperContext.Material.GetGenericPropertyValueMultiplied(GenericMaterialProperty.NormalTexture, 1f));
}
else
{
materialMapperContext.VirtualMaterial.DisableKeyword("_NORMALMAP");
}
CheckSpecularTexture(materialMapperContext);
}

private void CheckSpecularTexture(MaterialMapperContext materialMapperContext)
{
var specularTexturePropertyName = materialMapperContext.Material.GetGenericPropertyName(GenericMaterialProperty.SpecularTexture);
if (materialMapperContext.Material.HasProperty(specularTexturePropertyName))
{
LoadTexture(materialMapperContext, TextureType.Specular, materialMapperContext.Material.GetTextureValue(specularTexturePropertyName), ApplySpecGlossMapTexture);
}
else
{
ApplySpecGlossMapTexture(materialMapperContext, TextureType.Specular, null);
}
}

private void ApplySpecGlossMapTexture(MaterialMapperContext materialMapperContext, TextureType textureType, Texture texture)
{
materialMapperContext.VirtualMaterial.SetProperty("_SpecGlossMap", texture);
if (texture != null)
{
materialMapperContext.VirtualMaterial.EnableKeyword("_METALLICSPECGLOSSMAP");
}
else
{
materialMapperContext.VirtualMaterial.DisableKeyword("_METALLICSPECGLOSSMAP");
}
CheckOcclusionMapTexture(materialMapperContext);
}

private void CheckOcclusionMapTexture(MaterialMapperContext materialMapperContext)
{
var occlusionMapTextureName = materialMapperContext.Material.GetGenericPropertyName(GenericMaterialProperty.OcclusionTexture);
if (materialMapperContext.Material.HasProperty(occlusionMapTextureName))
{
LoadTexture(materialMapperContext, TextureType.Occlusion, materialMapperContext.Material.GetTextureValue(occlusionMapTextureName), ApplyOcclusionMapTexture);
}
else
{
ApplyOcclusionMapTexture(materialMapperContext, TextureType.Occlusion, null);
}
}

private void ApplyOcclusionMapTexture(MaterialMapperContext materialMapperContext, TextureType textureType, Texture texture)
{
materialMapperContext.VirtualMaterial.SetProperty("_OcclusionMap", texture);
if (texture != null)
{
materialMapperContext.VirtualMaterial.EnableKeyword("_OCCLUSIONMAP");
}
else
{
materialMapperContext.VirtualMaterial.DisableKeyword("_OCCLUSIONMAP");
}
CheckParallaxMapTexture(materialMapperContext);
}

private void CheckParallaxMapTexture(MaterialMapperContext materialMapperContext)
{
var parallaxMapTextureName = materialMapperContext.Material.GetGenericPropertyName(GenericMaterialProperty.ParallaxMap);
if (materialMapperContext.Material.HasProperty(parallaxMapTextureName))
{
LoadTexture(materialMapperContext, TextureType.Parallax, materialMapperContext.Material.GetTextureValue(parallaxMapTextureName), ApplyParallaxMapTexture);
}
else
{
ApplyParallaxMapTexture(materialMapperContext, TextureType.Parallax, null);
}
}

private void ApplyParallaxMapTexture(MaterialMapperContext materialMapperContext, TextureType textureType, Texture texture)
{
materialMapperContext.VirtualMaterial.SetProperty("_ParallaxMap", texture);
if (texture)
{
materialMapperContext.VirtualMaterial.EnableKeyword("_PARALLAXMAP");
}
else
{
materialMapperContext.VirtualMaterial.DisableKeyword("_PARALLAXMAP");
}
CheckMetallicGlossMapTexture(materialMapperContext);
}

private void CheckMetallicGlossMapTexture(MaterialMapperContext materialMapperContext)
{
var metallicGlossMapTextureName = materialMapperContext.Material.GetGenericPropertyName(GenericMaterialProperty.MetallicGlossMap);
if (materialMapperContext.Material.HasProperty(metallicGlossMapTextureName))
{
LoadTexture(materialMapperContext, TextureType.Metalness, materialMapperContext.Material.GetTextureValue(metallicGlossMapTextureName), ApplyMetallicGlossMapTexture);
}
else
{
ApplyMetallicGlossMapTexture(materialMapperContext, TextureType.Metalness, null);
}
}

private void ApplyMetallicGlossMapTexture(MaterialMapperContext materialMapperContext, TextureType textureType, Texture texture)
{
materialMapperContext.VirtualMaterial.SetProperty("_MetallicGlossMap", texture);
if (texture != null)
{
materialMapperContext.VirtualMaterial.EnableKeyword("_METALLICGLOSSMAP");
}
else
{
materialMapperContext.VirtualMaterial.DisableKeyword("_METALLICGLOSSMAP");
}
CheckEmissionColor(materialMapperContext);
}

private void CheckEmissionColor(MaterialMapperContext materialMapperContext)
{
var value = materialMapperContext.Material.GetGenericColorValue(GenericMaterialProperty.EmissionColor) * materialMapperContext.Material.GetGenericPropertyValueMultiplied(GenericMaterialProperty.EmissionColor, 1f);
materialMapperContext.VirtualMaterial.SetProperty("_EmissionColor", value);
if (value != Color.black)
{
materialMapperContext.VirtualMaterial.EnableKeyword("_EMISSION");
materialMapperContext.VirtualMaterial.GlobalIlluminationFlags = MaterialGlobalIlluminationFlags.RealtimeEmissive;
}
else
{
materialMapperContext.VirtualMaterial.DisableKeyword("_EMISSION");
materialMapperContext.VirtualMaterial.GlobalIlluminationFlags = MaterialGlobalIlluminationFlags.EmissiveIsBlack;
}
CheckDiffuseColor(materialMapperContext);
}

private void CheckDiffuseColor(MaterialMapperContext materialMapperContext)
{
var value = materialMapperContext.Material.GetGenericColorValue(GenericMaterialProperty.DiffuseColor) * materialMapperContext.Material.GetGenericPropertyValueMultiplied(GenericMaterialProperty.DiffuseColor, 1f);
value.a *= materialMapperContext.Material.GetGenericFloatValue(GenericMaterialProperty.AlphaValue);
if (!materialMapperContext.VirtualMaterial.HasAlpha && value.a < 1f)
{
materialMapperContext.VirtualMaterial.HasAlpha = true;
}
materialMapperContext.VirtualMaterial.SetProperty("_BaseColor", value);
BuildMaterial(materialMapperContext);
}
}

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
protected void BuildMaterial(MaterialMapperContext materialMapperContext) => materialMapperContext.UnityMaterial = this.InstantiateSuitableMaterial(materialMapperContext);

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);
else if ((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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public static UnityWebRequest CreateWebRequest(string uri, HttpRequestMethod httpRequestMethod = HttpRequestMethod.Get, string data = null, int timeout = 2000)
{
UnityWebRequest unityWebRequest;
switch (httpRequestMethod)
{
case HttpRequestMethod.Post:
unityWebRequest = UnityWebRequest.Post(uri, data);
break;
case HttpRequestMethod.Put:
unityWebRequest = UnityWebRequest.Put(uri, data);
break;
case HttpRequestMethod.Delete:
unityWebRequest = UnityWebRequest.Delete($"{uri}?{data}");
break;
case HttpRequestMethod.Head:
unityWebRequest = UnityWebRequest.Head($"{uri}?{data}");
break;
default:
unityWebRequest = UnityWebRequest.Get($"{uri}?{data}");
break;
}
unityWebRequest.timeout = timeout;
return unityWebRequest;
}

LoadModelFromUri

This method is the core and is defined as:

1
2
3
4
5
6
public static Coroutine LoadModelFromUri(UnityWebRequest unityWebRequest, Action<AssetLoaderContext> onLoad, Action<AssetLoaderContext> onMaterialsLoad, Action<AssetLoaderContext, float> onProgress, Action<IContextualizedError> onError = null, GameObject wrapperGameObject = null, AssetLoaderOptions assetLoaderOptions = null, object customContextData = null, string fileExtension = null, bool? isZipFile = null)
{
var assetDownloader = new GameObject("Asset Downloader").AddComponent<AssetDownloaderBehaviour>();
return assetDownloader.StartCoroutine(assetDownloader.DownloadAsset(unityWebRequest, onLoad, onMaterialsLoad, onProgress, wrapperGameObject, onError, assetLoaderOptions, customContextData, fileExtension, isZipFile));
}

This method mainly calls DownloadAsset.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
public IEnumerator DownloadAsset(UnityWebRequest unityWebRequest, Action<AssetLoaderContext> onLoad, Action<AssetLoaderContext> onMaterialsLoad, Action<AssetLoaderContext, float> onProgress, GameObject wrapperGameObject, Action<IContextualizedError> onError, AssetLoaderOptions assetLoaderOptions, object customContextData, string fileExtension, bool? isZipFile = null)
{
_unityWebRequest = unityWebRequest;
_onProgress = onProgress;
yield return unityWebRequest.SendWebRequest();
if (unityWebRequest.responseCode < 400)
{
var memoryStream = new MemoryStream(_unityWebRequest.downloadHandler.data);
var uriLoadCustomContextData = new UriLoadCustomContextData
{
UnityWebRequest = _unityWebRequest,
CustomData = customContextData
};
var contentType = unityWebRequest.GetResponseHeader("Content-Type");
if (contentType != null && isZipFile null)
{
isZipFile = contentType.Contains("application/zip") || contentType.Contains("application/x-zip-compressed") || contentType.Contains("multipart/x-zip");
}
if (isZipFile.GetValueOrDefault())
{
_assetLoaderContext = AssetLoaderZip.LoadModelFromZipStream(memoryStream, onLoad, onMaterialsLoad, delegate (AssetLoaderContext assetLoaderContext, float progress) { onProgress?.Invoke(assetLoaderContext, 0.5f + progress * 0.5f); }, onError, wrapperGameObject, assetLoaderOptions, uriLoadCustomContextData, fileExtension);
}
else
{
_assetLoaderContext = AssetLoader.LoadModelFromStream(memoryStream, null, fileExtension, onLoad, onMaterialsLoad, delegate (AssetLoaderContext assetLoaderContext, float progress) { onProgress?.Invoke(assetLoaderContext, 0.5f + progress * 0.5f); }, onError, wrapperGameObject, assetLoaderOptions, uriLoadCustomContextData);
}
}
else
{
var exception = new Exception($"UnityWebRequest error:{unityWebRequest.error}, code:{unityWebRequest.responseCode}");
if (onError != null)
{
var contextualizedError = exception as IContextualizedError;
onError(contextualizedError ?? new ContextualizedError<AssetLoaderContext>(exception, null));
}
else
{
throw exception;
}
}
Destroy(gameObject);
}

Because ours is a zip file, so go into the logic:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public static AssetLoaderContext LoadModelFromZipStream(Stream stream, Action<AssetLoaderContext> onLoad, Action<AssetLoaderContext> onMaterialsLoad, Action<AssetLoaderContext, float> onProgress, Action<IContextualizedError> onError = null, GameObject wrapperGameObject = null, AssetLoaderOptions assetLoaderOptions = null, object customContextData = null, string fileExtension = null)
{
var memoryStream = SetupZipModelLoading(ref stream, null, onError, assetLoaderOptions, ref fileExtension, out var zipFile);
return AssetLoader.LoadModelFromStream(memoryStream, null, fileExtension, onLoad, delegate (AssetLoaderContext assetLoaderContext)
{
var zipLoadCustomContextData = assetLoaderContext.CustomData as ZipLoadCustomContextData;
zipLoadCustomContextData?.Stream.Close();
onMaterialsLoad?.Invoke(assetLoaderContext);
}, onProgress, OnError, wrapperGameObject, assetLoaderOptions, new ZipLoadCustomContextData
{
ZipFile = zipFile,
Stream = stream,
CustomData = customContextData
});
}

Continue calling’LoadModelFromStream ':

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
public static AssetLoaderContext LoadModelFromStream(Stream stream, string filename = null, string fileExtension = null, Action<AssetLoaderContext> onLoad = null, Action<AssetLoaderContext> onMaterialsLoad = null, Action<AssetLoaderContext, float> onProgress = null, Action<IContextualizedError> onError = null, GameObject wrapperGameObject = null, AssetLoaderOptions assetLoaderOptions = null, object customContextData = null)
{
#if UNITY_WEBGL
AssetLoaderContext assetLoaderContext = null;
try
{
assetLoaderContext = LoadModelFromStreamNoThread(stream, filename, fileExtension, onError, wrapperGameObject, assetLoaderOptions, customContextData);
onLoad(assetLoaderContext);
onMaterialsLoad(assetLoaderContext);
}
catch (Exception exception)
{
if (exception is IContextualizedError contextualizedError)
{
HandleError(contextualizedError);
}
else
{
HandleError(new ContextualizedError<AssetLoaderContext>(exception, null));
}
}
return assetLoaderContext;
#else
var assetLoaderContext = new AssetLoaderContext
{
Options = assetLoaderOptions null ? CreateDefaultLoaderOptions() : assetLoaderOptions,
Stream = stream,
FileExtension = fileExtension ?? FileUtils.GetFileExtension(filename, false),
BasePath = FileUtils.GetFileDirectory(filename),
WrapperGameObject = wrapperGameObject,
OnMaterialsLoad = onMaterialsLoad,
OnLoad = onLoad,
HandleError = HandleError,
OnError = onError,
CustomData = customContextData
};
assetLoaderContext.Tasks.Add(ThreadUtils.RunThread(assetLoaderContext, ref assetLoaderContext.CancellationToken, LoadModel, ProcessRootModel, HandleError, assetLoaderContext.Options.Timeout));
return assetLoaderContext;
#endif
}

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
private static void LoadModel(AssetLoaderContext assetLoaderContext)
{
if (assetLoaderContext.Options.MaterialMappers != null)
{
Array.Sort(assetLoaderContext.Options.MaterialMappers, (a, b) => a.CheckingOrder > b.CheckingOrder ? -1 : 1);
}
else if (assetLoaderContext.Options.ShowLoadingWarnings)
{
Debug.LogWarning("Your AssetLoaderOptions instance has no MaterialMappers. TriLib can't process materials without them.");
}
#if TRILIB_DRACO
GltfReader.DracoDecompressorCallback = DracoMeshLoader.DracoDecompressorCallback;
#endif
var fileExtension = assetLoaderContext.FileExtension ?? FileUtils.GetFileExtension(assetLoaderContext.Filename, false).ToLowerInvariant();
if (assetLoaderContext.Stream null)
{
var fileStream = new FileStream(assetLoaderContext.Filename, FileMode.Open);
assetLoaderContext.Stream = fileStream;
var reader = Readers.FindReaderForExtension(fileExtension);
if (reader != null)
{
assetLoaderContext.RootModel = reader.ReadStream(fileStream, assetLoaderContext, assetLoaderContext.Filename, assetLoaderContext.OnProgress);
}
}
else
{
var reader = Readers.FindReaderForExtension(fileExtension);
if (reader != null)
{
assetLoaderContext.RootModel = reader.ReadStream(assetLoaderContext.Stream, assetLoaderContext, null, assetLoaderContext.OnProgress);
}
}
}

Then there is ProcessRootModel, which first calls ProcessModel recursion to introduce the Model, and then ProcessTextures to process the map

1
2
3
4
5
6
7
8
9
10
11
12
private static void ProcessRootModel(AssetLoaderContext assetLoaderContext)
{
ProcessModel(assetLoaderContext);
if (assetLoaderContext.Async)
{
ThreadUtils.RunThread(assetLoaderContext, ref assetLoaderContext.CancellationToken, ProcessTextures, null, assetLoaderContext.HandleError ?? assetLoaderContext.OnError, assetLoaderContext.Options.Timeout);
}
else
{
ProcessTextures(assetLoaderContext);
}
}

The last step of the ProcessTextures is the ProcessMaterial, which calls the Map method of the MaterialMapper we selected earlier:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
private static void ProcessMaterials(AssetLoaderContext assetLoaderContext)
{
if (assetLoaderContext.Options.MaterialMappers != null)
{
foreach (var material in assetLoaderContext.RootModel.AllMaterials)
{
MaterialMapper usedMaterialMapper = null;
var materialMapperContext = new MaterialMapperContext
{
Context = assetLoaderContext,
Material = material
};
foreach (var materialMapper in assetLoaderContext.Options.MaterialMappers)
{
if (materialMapper null || !materialMapper.IsCompatible(materialMapperContext))
{
continue;
}
materialMapper.Map(materialMapperContext);
usedMaterialMapper = materialMapper;
break;
}
if (usedMaterialMapper != null)
{
if (assetLoaderContext.MaterialRenderers.TryGetValue(material, out var materialRendererList))
{
foreach (var materialRendererContext in materialRendererList)
{
usedMaterialMapper.ApplyMaterialToRenderer(materialRendererContext, materialMapperContext);
}
}
}
}
}
else if (assetLoaderContext.Options.ShowLoadingWarnings)
{
Debug.LogWarning("The given AssetLoaderOptions contains no MaterialMapper. Materials will not be created.");
}
}

Also note that the’ApplyMaterialToRenderer 'method is also called here, which creates a new Material:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public void ApplyMaterialToRenderer(
MaterialRendererContext materialRendererContext,
MaterialMapperContext materialMapperContext)
{
Material[] sharedMaterials = materialRendererContext.Renderer.sharedMaterials;
sharedMaterials[materialRendererContext.MaterialIndex] = materialMapperContext.UnityMaterial;
materialRendererContext.Renderer.sharedMaterials = sharedMaterials;
if ((!materialMapperContext.Context.Options.UseAlphaMaterials || !materialMapperContext.VirtualMaterial.HasAlpha ? 0 : (!this.ForceStandardMaterial ? 1 : 0)) 0 || !materialMapperContext.Context.Options.AddSecondAlphaMaterial)
return;
MeshFilter componentInChildren1 = materialRendererContext.Renderer.GetComponentInChildren<MeshFilter>();
SkinnedMeshRenderer componentInChildren2 = materialRendererContext.Renderer.GetComponentInChildren<SkinnedMeshRenderer>();
Mesh mesh = (UnityEngine.Object) componentInChildren1 != (UnityEngine.Object) null ? componentInChildren1.sharedMesh : componentInChildren2?.sharedMesh;
if (!((UnityEngine.Object) mesh != (UnityEngine.Object) null))
return;
Material material = this.InstantiateSuitableSecondPassMaterial(materialMapperContext);
if ((UnityEngine.Object) material (UnityEngine.Object) null)
return;
int[] triangles = mesh.GetTriangles(materialRendererContext.MaterialIndex);
++mesh.subMeshCount;
mesh.SetTriangles(triangles, mesh.subMeshCount - 1);
List<Material> m = new List<Material>();
materialRendererContext.Renderer.GetSharedMaterials(m);
m.Add(material);
materialRendererContext.Renderer.materials = m.ToArray();
}

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
private void ApplyDiffuseMapTexture(TextureLoadingContext textureLoadingContext)
{
if (textureLoadingContext.UnityTexture != null)
{
Texture2D unityTexture = new Texture2D(textureLoadingContext.UnityTexture.width, textureLoadingContext.UnityTexture.height, textureLoadingContext.UnityTexture.graphicsFormat, textureLoadingContext.UnityTexture.mipmapCount, TextureCreationFlags.None);

Graphics.CopyTexture(textureLoadingContext.UnityTexture, unityTexture);
DestroyImmediate(textureLoadingContext.UnityTexture);
textureLoadingContext.UnityTexture = unityTexture;
textureLoadingContext.Context.AddUsedTexture(textureLoadingContext.UnityTexture);
}
textureLoadingContext.MaterialMapperContext.VirtualMaterial.SetProperty("_BaseMap", textureLoadingContext.UnityTexture, GenericMaterialProperty.DiffuseMap);
}