-
Notifications
You must be signed in to change notification settings - Fork 475
/
ImporterTextures.cs
592 lines (520 loc) · 19.1 KB
/
ImporterTextures.cs
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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
using System;
using System.IO;
using System.Threading.Tasks;
using GLTF.Schema;
using GLTF.Utilities;
using UnityEditor;
using UnityEngine;
using UnityGLTF.Cache;
using UnityGLTF.Extensions;
using UnityGLTF.Loader;
using UnityGLTF.Plugins;
using Object = UnityEngine.Object;
namespace UnityGLTF
{
public partial class GLTFSceneImporter
{
internal const string EMPTY_TEXTURE_NAME_SUFFIX = " \0";
private class TextureData
{
public Texture Texture = null;
public int TexCoord = 0;
public double DataMultiplier = 1;
public Vector2 Offset = Vector2.zero;
public double Rotation = 0;
public Vector2 Scale = Vector2.one;
public Nullable<int> TexCoordExtra = 0;
}
private async Task CreateNotReferencedTexture(int index)
{
if (Root.Textures[index].Source != null
&& Root.Images.Count > 0
&& Root.Images.Count > Root.Textures[index].Source.Id
&& string.IsNullOrEmpty(Root.Textures[index].Source.Value.Uri))
{
await ConstructImageBuffer(Root.Textures[index], index);
await ConstructTexture(Root.Textures[index], index, !KeepCPUCopyOfTexture, true, false);
}
}
private async Task<TextureData> FromTextureInfo(TextureInfo textureInfo, bool isNormal)
{
var result = new TextureData();
if (textureInfo?.Index?.Value == null) return result;
TextureId textureId = textureInfo.Index;
await ConstructTexture(textureId.Value, textureId.Id, !KeepCPUCopyOfTexture, true, isNormal);
result.Texture = _assetCache.TextureCache[textureId.Id].Texture;
result.TexCoord = textureInfo.TexCoord;
if (textureInfo is NormalTextureInfo nti)
result.DataMultiplier = nti.Scale;
if (textureInfo is OcclusionTextureInfo oti)
result.DataMultiplier = oti.Strength;
var ext = GetTextureTransform(textureInfo);
if (ext != null)
{
result.Offset = ext.Offset.ToUnityVector2Raw();
result.Rotation = ext.Rotation;
result.Scale = ext.Scale.ToUnityVector2Raw();
result.TexCoordExtra = ext.TexCoord;
}
return result;
}
protected async Task ConstructImage(GLTFImage image, int imageCacheIndex, bool markGpuOnly, bool isLinear, bool isNormal)
{
if (_assetCache.InvalidImageCache[imageCacheIndex])
return;
if (_assetCache.ImageCache[imageCacheIndex] == null)
{
Stream stream = null;
if (image.Uri == null)
{
var bufferView = image.BufferView.Value;
var data = new byte[bufferView.ByteLength];
BufferCacheData bufferContents = _assetCache.BufferCache[bufferView.Buffer.Id];
bufferContents.Stream.Position = bufferView.ByteOffset + bufferContents.ChunkOffset;
stream = new SubStream(bufferContents.Stream, 0, data.Length);
}
else
{
string uri = image.Uri;
byte[] bufferData;
URIHelper.TryParseBase64(uri, out bufferData);
if (bufferData != null)
{
stream = new MemoryStream(bufferData, 0, bufferData.Length, false, true);
}
else
{
stream = _assetCache.ImageStreamCache[imageCacheIndex];
}
}
await YieldOnTimeoutAndThrowOnLowMemory();
await ConstructUnityTexture(stream, markGpuOnly, isLinear, isNormal, image, imageCacheIndex);
}
}
protected async Task ConstructImageBuffer(GLTFTexture texture, int textureIndex)
{
int sourceId = GetTextureSourceId(texture);
if (_assetCache.ImageStreamCache[sourceId] == null)
{
GLTFImage image = _gltfRoot.Images[sourceId];
// we only load the streams if not a base64 uri, meaning the data is in the uri
if (image.Uri != null && !URIHelper.IsBase64Uri(image.Uri))
{
_assetCache.ImageStreamCache[sourceId] = await _options.DataLoader.LoadStreamAsync(image.Uri);
}
else if (image.Uri == null && image.BufferView != null && _assetCache.BufferCache[image.BufferView.Value.Buffer.Id] == null)
{
int bufferIndex = image.BufferView.Value.Buffer.Id;
await ConstructBuffer(_gltfRoot.Buffers[bufferIndex], bufferIndex);
}
}
if (_assetCache.TextureCache[textureIndex] == null)
{
_assetCache.TextureCache[textureIndex] = new TextureCacheData
{
TextureDefinition = texture
};
}
}
// With using KTX, we need to return a new Texture2D instance at the moment. Unity KTX package does not support loading into existing one
async Task<Texture2D> CheckMimeTypeAndLoadImage(GLTFImage image, Texture2D texture, byte[] data, bool markGpuOnly)
{
switch (image.MimeType)
{
case "image/png":
case "image/jpeg":
// NOTE: the second parameter of LoadImage() marks non-readable, but we can't mark it until after we call Apply()
texture.LoadImage(data, markGpuOnly);
break;
case "image/exr":
Debug.Log(LogType.Warning, $"EXR images are not supported. The texture {texture.name} won't be imported. glTF filename: {_gltfFileName}");
break;
case "image/ktx2":
string textureName = texture.name;
#if HAVE_KTX
if (Context.TryGetPlugin<Ktx2ImportContext>(out _))
{
#if UNITY_EDITOR
Texture.DestroyImmediate(texture);
#else
Texture.Destroy(texture);
#endif
var ktxTexture = new KtxUnity.KtxTexture();
using (var alloc = new Unity.Collections.NativeArray<byte>(data, Unity.Collections.Allocator.Persistent))
{
var resultTextureData = await ktxTexture.LoadFromBytes(alloc, false);
texture = resultTextureData.texture;
texture.name = textureName;
}
ktxTexture.Dispose();
}
else
#endif
{
Debug.Log(LogType.Warning, $"Can't import texture \"{image.Name}\" from \"{_gltfFileName}\" because it is a KTX2 file using the KHR_texture_basisu extension. Please add the package \"com.atteneder.ktx\" version v1.3+ to your project to import KTX2 textures.");
await Task.CompletedTask;
texture = null;
}
break;
default:
texture.LoadImage(data, markGpuOnly);
break;
}
// assign default values
if (texture)
{
texture.wrapMode = TextureWrapMode.Repeat;
texture.wrapModeV = TextureWrapMode.Repeat;
texture.wrapModeU = TextureWrapMode.Repeat;
texture.filterMode = FilterMode.Bilinear;
}
await Task.CompletedTask;
return texture;
}
protected virtual async Task ConstructUnityTexture(Stream stream, bool markGpuOnly, bool isLinear, bool isNormal, GLTFImage image, int imageCacheIndex)
{
bool convertToDxt5nmFormat = false;
#if UNITY_EDITOR
if (stream is AssetDatabaseStream assetDatabaseStream)
{
var tx = UnityEditor.AssetDatabase.LoadAssetAtPath<Texture2D>(assetDatabaseStream.AssetUri);
progressStatus.TextureLoaded++;
progress?.Report(progressStatus);
_assetCache.ImageCache[imageCacheIndex] = tx;
return;
}
if (isNormal && Context.SourceImporter != null)
{
BuildTargetGroup activeTargetGroup = BuildPipeline.GetBuildTargetGroup(EditorUserBuildSettings.activeBuildTarget);
if (PlayerSettings.GetNormalMapEncoding(activeTargetGroup) == NormalMapEncoding.DXT5nm)
{
convertToDxt5nmFormat = true;
}
}
#endif
Texture2D texture = new Texture2D(4, 4, TextureFormat.RGBA32, GenerateMipMapsForTextures, isLinear);
texture.name = string.IsNullOrEmpty(image.Name) ? Path.GetFileNameWithoutExtension(image.Uri) : image.Name;
if (string.IsNullOrEmpty(texture.name))
texture.name = $"Texture_{imageCacheIndex.ToString()}{EMPTY_TEXTURE_NAME_SUFFIX}";
var newTextureObject = texture;
#if UNITY_EDITOR
var haveRemappedTexture = false;
if (Context.SourceImporter != null)
{
// check for remapping, we don't even need to attempt loading the texture in that case.
var externalObjects = Context.SourceImporter.GetExternalObjectMap();
var sourceIdentifier = new AssetImporter.SourceAssetIdentifier(texture);
externalObjects.TryGetValue(sourceIdentifier, out var o);
if (o is Texture2D remappedTexture)
{
if (remappedTexture)
{
texture = remappedTexture;
haveRemappedTexture = true;
}
else
{
Context.SourceImporter.RemoveRemap(sourceIdentifier);
}
}
}
if (haveRemappedTexture)
{
// nothing to do here, the texture has already been remapped
}
else
#endif
if (stream is FileLoader.InvalidStream invalidStream)
{
// ignore - we still need a valid texture so that we can properly remap
// texture = null;
// We need some way to track these mock textures, so that we can get rid of them again after import
// TODO we should still set it to null here, and save the importer definition names for remapping instead.
// This way here we'll get into weird code for Runtime import, as we would still import mock textures...
// Or we add another option to avoid that.
texture = null;
UnityEngine.Debug.LogError("Buffer file " + invalidStream.RelativeFilePath + " not found in path: " + invalidStream.AbsoluteFilePath);
}
else if (stream is MemoryStream)
{
using (MemoryStream memoryStream = stream as MemoryStream)
{
await YieldOnTimeoutAndThrowOnLowMemory();
texture = await CheckMimeTypeAndLoadImage(image, texture, memoryStream.ToArray(), markGpuOnly);
}
}
else
{
byte[] buffer = new byte[stream.Length];
// todo: potential optimization is to split stream read into multiple frames (or put it on a thread?)
if (stream.Length > int.MaxValue)
{
throw new Exception("Stream is larger than can be copied into byte array");
}
stream.Read(buffer, 0, (int)stream.Length);
await YieldOnTimeoutAndThrowOnLowMemory();
texture = await CheckMimeTypeAndLoadImage(image, texture, buffer, markGpuOnly);
}
if (texture && convertToDxt5nmFormat)
{
await NormalMapEncodingConverter.ConvertToDxt5nmAsync(texture);
texture.Apply();
}
if (!texture)
_assetCache.InvalidImageCache[imageCacheIndex] = newTextureObject;
if (_assetCache.ImageCache[imageCacheIndex] != null) Debug.Log(LogType.Assert, "ImageCache should not be loaded multiple times");
if (texture)
{
progressStatus.TextureLoaded++;
progress?.Report(progressStatus);
}
_assetCache.ImageCache[imageCacheIndex] = texture;
}
protected virtual int GetTextureSourceId(GLTFTexture texture)
{
if (texture.Extensions != null && texture.Extensions.ContainsKey(KHR_texture_basisu.EXTENSION_NAME))
{
return ((KHR_texture_basisu)texture.Extensions[KHR_texture_basisu.EXTENSION_NAME]).source.Id;
}
return texture.Source?.Id ?? 0;
}
protected virtual bool IsTextureFlipped(GLTFTexture texture)
{
if (texture.Extensions != null && texture.Extensions.ContainsKey(KHR_texture_basisu.EXTENSION_NAME))
{
return true;
}
return false;
}
/// <summary>
/// Creates a texture from a glTF texture
/// </summary>
/// <param name="texture">The texture to load</param>
/// <param name="textureIndex">The index in the texture cache</param>
/// <param name="markGpuOnly">Whether the texture is GPU only, instead of keeping a CPU copy</param>
/// <param name="isLinear">Whether the texture is linear rather than sRGB</param>
/// <returns>The loading task</returns>
public virtual async Task LoadTextureAsync(GLTFTexture texture, int textureIndex, bool markGpuOnly, bool isLinear)
{
try
{
lock (this)
{
if (_isRunning)
{
throw new GLTFLoadException("Cannot CreateTexture while GLTFSceneImporter is already running");
}
_isRunning = true;
}
if (_options.ThrowOnLowMemory)
{
_memoryChecker = new MemoryChecker();
}
if (_gltfRoot == null)
{
await LoadJson(_gltfFileName);
}
if (_assetCache == null)
{
_assetCache = new AssetCache(_gltfRoot);
}
await ConstructImageBuffer(texture, textureIndex);
await ConstructTexture(texture, textureIndex, markGpuOnly, isLinear, false);
}
finally
{
lock (this)
{
_isRunning = false;
}
_gltfStream.Stream.Close();
}
}
public virtual Task LoadTextureAsync(GLTFTexture texture, int textureIndex, bool isLinear)
{
return LoadTextureAsync(texture, textureIndex, !KeepCPUCopyOfTexture, isLinear);
}
/// <summary>
/// Gets texture that has been loaded from CreateTexture
/// </summary>
/// <param name="textureIndex">The texture to get</param>
/// <returns>Created texture</returns>
public virtual Texture GetTexture(int textureIndex)
{
if (_assetCache == null)
{
throw new GLTFLoadException("Asset cache needs initialized before calling GetTexture");
}
if (_assetCache.TextureCache[textureIndex] == null)
{
return null;
}
return _assetCache.TextureCache[textureIndex].Texture;
}
protected virtual async Task ConstructTexture(GLTFTexture texture, int textureIndex, bool markGpuOnly, bool isLinear, bool isNormal)
{
if (_assetCache.TextureCache[textureIndex].Texture == null)
{
int sourceId = GetTextureSourceId(texture);
GLTFImage image = _gltfRoot.Images[sourceId];
await ConstructImage(image, sourceId, markGpuOnly, isLinear, isNormal);
var source = _assetCache.ImageCache[sourceId];
if (!source) return;
FilterMode desiredFilterMode;
TextureWrapMode desiredWrapModeS, desiredWrapModeT;
if (texture.Sampler != null)
{
var sampler = texture.Sampler.Value;
switch (sampler.MinFilter)
{
case MinFilterMode.Nearest:
case MinFilterMode.NearestMipmapNearest:
case MinFilterMode.NearestMipmapLinear:
desiredFilterMode = FilterMode.Point;
break;
case MinFilterMode.Linear:
case MinFilterMode.LinearMipmapNearest:
desiredFilterMode = FilterMode.Bilinear;
break;
case MinFilterMode.LinearMipmapLinear:
desiredFilterMode = FilterMode.Trilinear;
break;
default:
Debug.Log(LogType.Warning, "Unsupported Sampler.MinFilter: " + sampler.MinFilter);
desiredFilterMode = FilterMode.Trilinear;
break;
}
TextureWrapMode UnityWrapMode(GLTF.Schema.WrapMode gltfWrapMode)
{
switch (gltfWrapMode)
{
case GLTF.Schema.WrapMode.ClampToEdge:
return TextureWrapMode.Clamp;
case GLTF.Schema.WrapMode.Repeat:
return TextureWrapMode.Repeat;
case GLTF.Schema.WrapMode.MirroredRepeat:
return TextureWrapMode.Mirror;
default:
Debug.Log(LogType.Warning, "Unsupported Sampler.Wrap: " + gltfWrapMode);
return TextureWrapMode.Repeat;
}
}
desiredWrapModeS = UnityWrapMode(sampler.WrapS);
desiredWrapModeT = UnityWrapMode(sampler.WrapT);
}
else
{
desiredFilterMode = FilterMode.Trilinear;
desiredWrapModeS = TextureWrapMode.Repeat;
desiredWrapModeT = TextureWrapMode.Repeat;
}
var matchSamplerState = source.filterMode == desiredFilterMode && source.wrapModeU == desiredWrapModeS && source.wrapModeV == desiredWrapModeT;
if (matchSamplerState || markGpuOnly)
{
if (_assetCache.TextureCache[textureIndex].Texture != null) Debug.Log(LogType.Assert, "Texture should not be reset to prevent memory leaks");
_assetCache.TextureCache[textureIndex].Texture = source;
if (!matchSamplerState)
{
Debug.Log(LogType.Warning, $"Ignoring sampler; filter mode: source {source.filterMode}, desired {desiredFilterMode}; wrap mode: source {source.wrapModeU}x{source.wrapModeV}, desired {desiredWrapModeS}x{desiredWrapModeT}");
}
}
else
#if UNITY_EDITOR
if (!UnityEditor.AssetDatabase.Contains(source))
#endif
{
Texture2D unityTexture;
if (!source.isReadable)
{
unityTexture = new Texture2D(source.width, source.height, source.format, source.mipmapCount, isLinear);
Graphics.CopyTexture(source, unityTexture);
}
else
unityTexture = Object.Instantiate(source);
unityTexture.name = string.IsNullOrEmpty(image.Name) ?
string.IsNullOrEmpty(texture.Name) ?
Path.GetFileNameWithoutExtension(image.Uri) :
texture.Name :
image.Name;
if (string.IsNullOrEmpty(unityTexture.name))
unityTexture.name = $"Texture_{textureIndex.ToString()}{EMPTY_TEXTURE_NAME_SUFFIX}";
unityTexture.filterMode = desiredFilterMode;
unityTexture.wrapModeU = desiredWrapModeS;
unityTexture.wrapModeV = desiredWrapModeT;
if (_assetCache.TextureCache[textureIndex].Texture != null) Debug.Log(LogType.Assert, "Texture should not be reset to prevent memory leaks");
_assetCache.TextureCache[textureIndex].Texture = unityTexture;
}
#if UNITY_EDITOR
else
{
// don't warn for just filter mode, user choice
if (source.wrapModeU != desiredWrapModeS || source.wrapModeV != desiredWrapModeT)
Debug.Log(LogType.Warning, ($"Sampler state doesn't match but source texture is non-readable. Results might not be correct if textures are used multiple times with different sampler states. {source.filterMode} == {desiredFilterMode} && {source.wrapModeU} == {desiredWrapModeS} && {source.wrapModeV} == {desiredWrapModeT}"));
_assetCache.TextureCache[textureIndex].Texture = source;
}
#endif
}
_assetCache.TextureCache[textureIndex].IsLinear = isLinear;
_assetCache.TextureCache[textureIndex].IsNormal = isNormal;
try
{
var tex = _assetCache.TextureCache[textureIndex].Texture;
foreach (var plugin in Context.Plugins)
{
plugin.OnAfterImportTexture(texture, textureIndex, tex);
}
}
catch (Exception ex)
{
Debug.LogException(ex);
}
}
protected virtual void ConstructImageFromGLB(GLTFImage image, int imageCacheIndex)
{
var texture = new Texture2D(0, 0);
texture.name = nameof(GLTFSceneImporter) + (image.Name != null ? ("." + image.Name) : "");
var bufferView = image.BufferView.Value;
var data = new byte[bufferView.ByteLength];
var bufferContents = _assetCache.BufferCache[bufferView.Buffer.Id];
bufferContents.Stream.Position = bufferView.ByteOffset + bufferContents.ChunkOffset;
bufferContents.Stream.Read(data, 0, data.Length);
texture.LoadImage(data);
if (_assetCache.ImageCache[imageCacheIndex] != null) Debug.Log(LogType.Assert, "ImageCache should not be loaded multiple times");
progressStatus.TextureLoaded++;
progress?.Report(progressStatus);
_assetCache.ImageCache[imageCacheIndex] = texture;
}
#if UNITY_EDITOR
internal class AssetDatabaseStream : Stream
{
public string AssetUri { get; }
public AssetDatabaseStream(string imageUri)
{
AssetUri = imageUri;
}
public override void Flush() => throw new NotImplementedException();
public override int Read(byte[] buffer, int offset, int count) => throw new NotImplementedException();
public override long Seek(long offset, SeekOrigin origin) => throw new NotImplementedException();
public override void SetLength(long value) => throw new NotImplementedException();
public override void Write(byte[] buffer, int offset, int count) => throw new NotImplementedException();
public override bool CanRead { get; }
public override bool CanSeek { get; }
public override bool CanWrite { get; }
public override long Length { get; }
public override long Position { get; set; }
}
#endif
}
internal static class MatHelper
{
internal static void SetKeyword(this Material material, string keyword, bool state)
{
if (state)
material.EnableKeyword(keyword + "_ON");
else
material.DisableKeyword(keyword + "_ON");
if (material.HasProperty(keyword))
material.SetFloat(keyword, state ? 1 : 0);
}
}
}