/
GltfShape.cs
1887 lines (1713 loc) · 113 KB
/
GltfShape.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
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// COPYRIGHT 2014 by the Open Rails project.
//
// This file is part of Open Rails.
//
// Open Rails is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Open Rails is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Open Rails. If not, see <http://www.gnu.org/licenses/>.
// This file is the responsibility of the 3D & Environment Team.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.ComponentModel;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Orts.Viewer3D.Common;
using Orts.Viewer3D.Processes;
using ORTS.Common;
using glTFLoader.Schema;
using Orts.Simulation.AIs;
namespace Orts.Viewer3D
{
public class GltfShape : SharedShape
{
public static bool EnableAnimations { get; set; }
public static List<string> ExtensionsSupported = new List<string>
{
"KHR_lights_punctual",
"KHR_materials_unlit",
"KHR_materials_clearcoat",
"MSFT_lod",
"MSFT_texture_dds",
"MSFT_packing_normalRoughnessMetallic",
"MSFT_packing_occlusionRoughnessMetallic",
};
string FileDir { get; set; }
int SkeletonRootNode;
public bool MsfsFlavoured;
internal Vector3[] Scales;
internal Quaternion[] Rotations;
internal Vector3[] Translations;
internal float[][] Weights;
/// <summary>
/// glTF specification declares that the model's forward is +Z. However OpenRails uses -Z as forward,
/// so we need to apply a 180 degree rotation to turn around every model matrix to conform the spec.
/// </summary>
static Matrix PlusZToForward = Matrix.CreateFromAxisAngle(Vector3.UnitY, MathHelper.Pi);
static readonly string[] StandardTextureExtensionFilter = new[] { ".png", ".jpg", ".jpeg" };
static readonly string[] DdsTextureExtensionFilter = new[] { ".dds" };
public static Texture2D EnvironmentMapSpecularDay;
public static TextureCube EnvironmentMapDiffuseDay;
public static Texture2D BrdfLutTexture;
static readonly Dictionary<string, CubeMapFace> EnvironmentMapFaces = new Dictionary<string, CubeMapFace>
{
["px"] = CubeMapFace.PositiveX,
["nx"] = CubeMapFace.NegativeX,
["py"] = CubeMapFace.PositiveY,
["ny"] = CubeMapFace.NegativeY,
["pz"] = CubeMapFace.PositiveZ,
["nz"] = CubeMapFace.NegativeZ
};
readonly List<GltfAnimation> GltfAnimations = new List<GltfAnimation>();
public float[] MinimumScreenCoverages = new[] { 0f };
public readonly Vector4[] BoundingBoxNodes = new Vector4[8];
/// <summary>
/// All vertex buffers in a gltf file. The key is the accessor number.
/// </summary>
internal Dictionary<int, VertexBufferBinding> VertexBuffers = new Dictionary<int, VertexBufferBinding>();
internal Dictionary<int, byte[]> BinaryBuffers = new Dictionary<int, byte[]>();
/// <summary>
/// glTF shape from file
/// </summary>
/// <param name="viewer"></param>
/// <param name="filePath">Path to shape's glTF file</param>
public GltfShape(Viewer viewer, string filePath)
: base(viewer, filePath)
{
// In glTF the animation frames are measured in seconds, so the default FPS value must be 1 second per second.
CustomAnimationFPS = 1;
EnableAnimations = viewer.Game.Settings.GltfAnimations;
}
protected override void LoadContent()
{
Trace.Write("G");
var textureFlags = Helpers.TextureFlags.None;
Dictionary<int, string> externalLods = new Dictionary<int, string>();
FileDir = Path.GetDirectoryName(FilePath);
var inputFilename = Path.GetFileNameWithoutExtension(FilePath).ToUpper();
if (inputFilename.Contains("_LOD"))
inputFilename = inputFilename.Substring(0, inputFilename.Length - 6); // to strip the "_LOD00" from the end
var files = Directory.GetFiles(FileDir);
Match match;
foreach (var file in files)
{
if ((match = Regex.Match(Path.GetFileName(file.ToUpper()), inputFilename + @"_LOD(\d\d).GLTF$")).Success)
{
if (int.TryParse(match.Groups[1].Value, out var lod))
externalLods[lod] = file;
}
}
if (!externalLods.Any())
externalLods.Add(0, FilePath);
LodControls = new[] { new GltfLodControl(this, externalLods) };
if (EnvironmentMapSpecularDay == null)
{
// TODO: split the equirectangular specular panorama image to a cube map for saving the pixel shader instructions of converting the
// cartesian cooridinates to polar for sampling. Couldn't find a converter though, that also supports RGBD color encoding.
// RGBD is an encoding where a divider is stored in the alpha channel to reconstruct the High Dynamic Range of the RGB colors.
// A HDR to TGA-RGBD converter is available here: https://seenax.com/portfolio/cpp.php , this can be further converted to PNG by e.g. GIMP.
EnvironmentMapSpecularDay = Texture2D.FromStream(Viewer.GraphicsDevice, File.OpenRead(Path.Combine(Viewer.Game.ContentPath, "EnvMapDay/specular-RGBD.png")));
// Possible TODO: replace the diffuse map with spherical harmonics coefficients (9x float3), as defined in EXT_lights_image_based.
// See shader implementation e.g. here: https://github.com/CesiumGS/cesium/pull/7172
EnvironmentMapDiffuseDay = new TextureCube(Viewer.GraphicsDevice, 128, false, SurfaceFormat.ColorSRgb);
foreach (var face in EnvironmentMapFaces.Keys)
{
// How to do this more efficiently?
using (var stream = File.OpenRead(Path.Combine(Viewer.Game.ContentPath, $"EnvMapDay/diffuse_{face}_0.jpg")))
{
var tex = Texture2D.FromStream(Viewer.GraphicsDevice, stream);
var data = new Color[tex.Width * tex.Height];
tex.GetData(data);
EnvironmentMapDiffuseDay.SetData(EnvironmentMapFaces[face], data);
tex.Dispose();
}
}
}
if (BrdfLutTexture == null)
{
using (var stream = File.OpenRead(Path.Combine(Viewer.Game.ContentPath, $"EnvMapDay/brdfLUT.png")))
{
BrdfLutTexture = Texture2D.FromStream(Viewer.GraphicsDevice, stream);
}
}
}
public override Matrix SetRenderMatrices(ShapePrimitive baseShapePrimitive, Matrix[] animatedMatrices, ref Matrix tileTranslation, out Matrix[] bones)
{
var shapePrimitive = baseShapePrimitive as GltfPrimitive;
bones = Enumerable.Repeat(Matrix.Identity, Math.Min(RenderProcess.MAX_BONES, shapePrimitive.Joints.Length)).ToArray();
for (var j = 0; j < bones.Length; j++)
{
bones[j] = shapePrimitive.InverseBindMatrices[j];
var hi = shapePrimitive.Joints[j];
while (hi >= 0 && hi < shapePrimitive.Hierarchy.Length)
{
Matrix.Multiply(ref bones[j], ref animatedMatrices[hi], out bones[j]);
hi = shapePrimitive.Hierarchy[hi];
}
Matrix.Multiply(ref bones[j], ref PlusZToForward, out bones[j]);
// The ConsistGenerator is used to show all the Khronos sample models for testing purposes. However they need adjustments to show them all at once.
if (ConsistGenerator.GltfVisualTestRun && SampleModelsAdjustments.TryGetValue(Path.GetFileNameWithoutExtension(FilePath), out var adjustment))
Matrix.Multiply(ref bones[j], ref adjustment, out bones[j]);
Matrix.Multiply(ref bones[j], ref tileTranslation, out bones[j]);
}
// Skinned primitive
if (shapePrimitive.Joints.Length > 1)
return Matrix.Identity;
// Non-skinned primitive
var matrix = bones[0];
bones = null;
return matrix;
}
internal Func<BinaryReader, float> GetNormalizedReader(Accessor.ComponentTypeEnum componentType)
{
switch (componentType)
{
case Accessor.ComponentTypeEnum.UNSIGNED_BYTE: return (br) => br.ReadByte() / 255.0f;
case Accessor.ComponentTypeEnum.UNSIGNED_SHORT: return (br) => br.ReadUInt16() / 65535.0f;
case Accessor.ComponentTypeEnum.BYTE: return (br) => Math.Max(br.ReadSByte() / 127.0f, -1.0f);
// Component type 5122 "SHORT" is a 16 bit int by the glTF specification, but is used as a 16 bit float (half) by asobo-msfs:
case Accessor.ComponentTypeEnum.SHORT: return (br) => MsfsFlavoured ? ToTwoByteFloat(br.ReadBytes(2)) : Math.Max(br.ReadInt16() / 32767.0f, -1.0f); // the prior is br.ReadHalf() in fact
case Accessor.ComponentTypeEnum.FLOAT:
default: return (br) => br.ReadSingle();
}
}
internal static Func<BinaryReader, ushort> GetIntegerReader(AccessorSparseIndices.ComponentTypeEnum componentTypeEnum) => GetIntegerReader((Accessor.ComponentTypeEnum)componentTypeEnum);
internal static Func<BinaryReader, ushort> GetIntegerReader(Accessor.ComponentTypeEnum componentTypeEnum)
{
switch (componentTypeEnum)
{
case Accessor.ComponentTypeEnum.BYTE: return (br) => (ushort)br.ReadSByte();
case Accessor.ComponentTypeEnum.UNSIGNED_INT: return (br) => (ushort)br.ReadUInt32();
case Accessor.ComponentTypeEnum.UNSIGNED_BYTE: return (br) => br.ReadByte();
case Accessor.ComponentTypeEnum.UNSIGNED_SHORT:
default: return (br) => br.ReadUInt16();
}
}
static float ToTwoByteFloat(byte[] bytes) // Hi, Lo
{
var intVal = BitConverter.ToInt32(new byte[] { bytes[0], bytes[1], 0, 0 }, 0);
int mant = intVal & 0x03ff;
int exp = intVal & 0x7c00;
if (exp == 0x7c00) exp = 0x3fc00;
else if (exp != 0)
{
exp += 0x1c000;
if (mant == 0 && exp > 0x1c400)
return BitConverter.ToSingle(BitConverter.GetBytes((intVal & 0x8000) << 16 | exp << 13 | 0x3ff), 0);
}
else if (mant != 0)
{
exp = 0x1c400;
do
{
mant <<= 1;
exp -= 0x400;
} while ((mant & 0x400) == 0);
mant &= 0x3ff;
}
return BitConverter.ToSingle(BitConverter.GetBytes((intVal & 0x8000) << 16 | (exp | mant) << 13), 0);
}
public class GltfLodControl : LodControl
{
readonly Dictionary<string, Gltf> Gltfs = new Dictionary<string, Gltf>();
static readonly float[] DefaultScreenCoverages = new[] { 0.2f, 0.05f, 0.001f, 0f, 0f, 0f, 0f, 0f, 0f, 0f };
public GltfLodControl(GltfShape shape, Dictionary<int, string> externalLods)
{
var distanceLevels = new List<GltfDistanceLevel>();
foreach (var id in externalLods.Keys)
{
var gltfFile = glTFLoader.Interface.LoadModel(externalLods[id]);
Gltfs.Add(externalLods[id], gltfFile);
if (shape.MatrixNames.Count < (gltfFile.Animations?.Length ?? 0))
shape.MatrixNames.AddRange(Enumerable.Repeat("", gltfFile.Animations.Length - shape.MatrixNames.Count));
if (gltfFile.ExtensionsRequired != null)
{
var unsupportedExtensions = new List<string>();
foreach (var extensionRequired in gltfFile.ExtensionsRequired)
if (!ExtensionsSupported.Contains(extensionRequired))
unsupportedExtensions.Add($"\"{extensionRequired}\"");
if (unsupportedExtensions.Any())
Trace.TraceWarning($"glTF required extension {string.Join(", ", unsupportedExtensions)} is unsupported in file {externalLods[id]}");
}
if (gltfFile.Asset?.Extensions?.ContainsKey("ASOBO_asset_optimized") ?? false)
shape.MsfsFlavoured = true;
var internalLodsNumber = 0;
if (id == 0)
{
var rootNodeNumber = gltfFile.Scenes.ElementAtOrDefault(gltfFile.Scene ?? 0).Nodes?.First();
if (rootNodeNumber != null)
{
var rootNode = gltfFile.Nodes[(int)rootNodeNumber];
object extension = null;
if (rootNode.Extensions?.TryGetValue("MSFT_lod", out extension) ?? false)
{
var ext = Newtonsoft.Json.JsonConvert.DeserializeObject<MSFT_lod>(extension.ToString());
if (ext?.Ids != null)
internalLodsNumber = ext.Ids.Length + 1;
var screenCoverages = DefaultScreenCoverages;
if (rootNode.Extras?.TryGetValue("MSFT_screencoverage", out extension) ?? false)
screenCoverages = Newtonsoft.Json.JsonConvert.DeserializeObject<float[]>(extension.ToString());
shape.MinimumScreenCoverages = new float[internalLodsNumber];
Array.Copy(screenCoverages, shape.MinimumScreenCoverages, internalLodsNumber);
}
}
}
if (internalLodsNumber > 0)
{
for (var i = 0; i < internalLodsNumber; i++)
distanceLevels.Add(new GltfDistanceLevel(shape, i, gltfFile, externalLods[id]));
// Use the internal lods instead of the externals, if available.
break;
}
distanceLevels.Add(new GltfDistanceLevel(shape, id, gltfFile, externalLods[id]));
shape.BinaryBuffers.Clear();
shape.VertexBuffers.Clear();
}
DistanceLevels = distanceLevels.ToArray();
// Sweep the resources not used anymore
shape.BinaryBuffers = null;
shape.VertexBuffers = null;
}
}
public class GltfDistanceLevel : DistanceLevel
{
// See the glTF specification at https://www.khronos.org/registry/glTF/specs/2.0/glTF-2.0.html
readonly Gltf Gltf;
readonly string GltfDir;
readonly string GltfFileName;
Dictionary<int, byte[]> BinaryBuffers => Shape.BinaryBuffers;
/// <summary>
/// All inverse bind matrices in a gltf file. The key is the accessor number.
/// </summary>
internal Dictionary<int, Matrix[]> AllInverseBindMatrices = new Dictionary<int, Matrix[]>();
internal readonly ImmutableArray<Matrix> Matrices;
readonly ImmutableArray<Vector3> Scales;
readonly ImmutableArray<Quaternion> Rotations;
readonly ImmutableArray<Vector3> Translations;
readonly ImmutableArray<float[]> Weights;
internal readonly Viewer Viewer;
internal readonly GltfShape Shape;
static readonly Stack<int> TempStack = new Stack<int>(); // (nodeNumber, parentIndex)
static readonly string[] TestControls = new[] { "WIPER", "ORTSITEM1CONTINUOUS", "ORTSITEM2CONTINUOUS" };
public GltfDistanceLevel(GltfShape shape, int lodId, Gltf gltfFile, string gltfFileName)
{
ViewingDistance = float.MaxValue; // glTF is using screen coverage, so this one is set for not getting into the way accidentally
ViewSphereRadius = 100;
var morphWarning = false;
Shape = shape;
Viewer = shape.Viewer;
Gltf = gltfFile;
GltfDir = Path.GetDirectoryName(gltfFileName);
GltfFileName = gltfFileName;
KHR_lights gltfLights = null;
object extension = null;
if (gltfFile.Extensions?.TryGetValue("KHR_lights_punctual", out extension) ?? false)
gltfLights = Newtonsoft.Json.JsonConvert.DeserializeObject<KHR_lights>(extension.ToString());
Weights = gltfFile.Nodes.Select(node => gltfFile.Meshes?.ElementAtOrDefault(node.Mesh ?? -1)?.Weights).ToImmutableArray();
Scales = gltfFile.Nodes.Select(node => node.Scale == null ? Vector3.One : new Vector3(node.Scale[0], node.Scale[1], node.Scale[2])).ToImmutableArray();
Rotations = gltfFile.Nodes.Select(node => node.Rotation == null ? Quaternion.Identity : new Quaternion(node.Rotation[0], node.Rotation[1], node.Rotation[2], node.Rotation[3])).ToImmutableArray();
Translations = gltfFile.Nodes.Select(node => node.Translation == null ? Vector3.Zero : new Vector3(node.Translation[0], node.Translation[1], node.Translation[2])).ToImmutableArray();
Matrices = gltfFile.Nodes.Select((node, i) => node.Matrix == null ? Matrix.Identity : new Matrix(
node.Matrix[0], node.Matrix[1], node.Matrix[2], node.Matrix[3],
node.Matrix[4], node.Matrix[5], node.Matrix[6], node.Matrix[7],
node.Matrix[8], node.Matrix[9], node.Matrix[10], node.Matrix[11],
node.Matrix[12], node.Matrix[13], node.Matrix[14], node.Matrix[15])
* Matrix.CreateScale(Scales[i]) * Matrix.CreateFromQuaternion(Rotations[i]) * Matrix.CreateTranslation(Translations[i])).ToImmutableArray();
var hierarchy = Enumerable.Repeat(-1, gltfFile.Nodes.Length).ToArray();
var parents = new Dictionary<int, int>();
var lods = Enumerable.Repeat(-1, gltfFile.Nodes.Length).ToArray(); // -1: common; 0, 1, 3, etc.: the lod the node belongs to
Dictionary<int, (string name, float radius)> articulations = null;
var meshes = new Dictionary<int, Node>();
var lights = new Dictionary<int, KHR_lights_punctual>();
TempStack.Clear();
Array.ForEach(gltfFile.Scenes.ElementAtOrDefault(gltfFile.Scene ?? 0).Nodes, node => TempStack.Push(node));
while (TempStack.Any())
{
var nodeNumber = TempStack.Pop();
var node = gltfFile.Nodes[nodeNumber];
var parent = hierarchy[nodeNumber];
if (parent > -1 && lods[parent] > -1)
lods[nodeNumber] = lods[parent];
if (node.Children != null)
{
foreach (var child in node.Children)
{
hierarchy[child] = nodeNumber;
TempStack.Push(child);
}
}
if (node.Extensions?.TryGetValue("MSFT_lod", out extension) ?? false)
{
var ext = Newtonsoft.Json.JsonConvert.DeserializeObject<MSFT_lod>(extension.ToString());
var ids = ext?.Ids;
if (ids.Any())
{
lods[nodeNumber] = 0;
for (var j = 0; j < ids.Length; j++)
{
// The node defined in the MSFT_lod extension is a substitute of the current one, not an additional new step-to.
lods[ids[j]] = j + 1;
hierarchy[ids[j]] = parent;
TempStack.Push(ids[j]);
}
}
}
// Collect meshes and lights belonging to the common root or the specific lod only:
if (lods[nodeNumber] == -1 || lods[nodeNumber] == lodId)
{
if (node.Mesh != null)
meshes.Add(nodeNumber, node);
if (node.Extensions?.TryGetValue("KHR_lights_punctual", out extension) ?? false)
{
var lightId = Newtonsoft.Json.JsonConvert.DeserializeObject<KHR_lights_punctual_index>(extension.ToString())?.light;
if (lightId != null)
lights.Add(nodeNumber, gltfLights.lights[(int)lightId]);
}
if ((node.Extras?.TryGetValue("OPENRAILS_animation_name", out extension) ?? false) && extension is string name)
{
var radius = 0f;
if ((node.Extras?.TryGetValue("OPENRAILS_animation_wheelradius", out extension) ?? false) && extension is string wheelRadius)
float.TryParse(wheelRadius, out radius);
articulations = articulations ?? new Dictionary<int, (string, float)>();
articulations.Add(nodeNumber, (name, radius));
}
}
}
var subObjects = new List<SubObject>();
foreach (var hierIndex in meshes.Keys)
{
var node = meshes[hierIndex];
var mesh = gltfFile.Meshes[(int)node.Mesh];
var skin = node.Skin != null ? gltfFile.Skins[(int)node.Skin] : null;
for (var i = 0; i < mesh.Primitives.Length; i++)
subObjects.Add(new GltfSubObject(mesh.Primitives[i], $"{mesh.Name}[{i}]", hierIndex, hierarchy, Helpers.TextureFlags.None, gltfFile, shape, this, skin));
}
foreach (var hierIndex in lights.Keys)
{
subObjects.Add(new GltfSubObject(lights[hierIndex], hierIndex, hierarchy, gltfFile, shape, this));
}
SubObjects = subObjects.ToArray();
if (lodId == 0)
{
shape.Matrices = Matrices.ToArray();
shape.Scales = Scales.ToArray();
shape.Rotations = Rotations.ToArray();
shape.Translations = Translations.ToArray();
shape.Weights = Weights.ToArray();
if (SubObjects.FirstOrDefault() is GltfSubObject gltfSubObject)
{
var minPosition = Vector4.Transform(gltfSubObject.MinPosition, Matrices[gltfSubObject.HierarchyIndex]);
var maxPosition = Vector4.Transform(gltfSubObject.MaxPosition, Matrices[gltfSubObject.HierarchyIndex]);
foreach (GltfSubObject subObject in SubObjects.Cast<GltfSubObject>())
{
var soMinPosition = Vector4.Transform(subObject.MinPosition, Matrices[subObject.HierarchyIndex]);
var soMaxPosition = Vector4.Transform(subObject.MaxPosition, Matrices[subObject.HierarchyIndex]);
minPosition = Vector4.Min(minPosition, soMinPosition);
maxPosition = Vector4.Max(maxPosition, soMaxPosition);
}
shape.BoundingBoxNodes[0] = minPosition;
shape.BoundingBoxNodes[1] = new Vector4(minPosition.X, minPosition.Y, maxPosition.Z, 1);
shape.BoundingBoxNodes[2] = new Vector4(minPosition.X, maxPosition.Y, maxPosition.Z, 1);
shape.BoundingBoxNodes[3] = new Vector4(minPosition.X, maxPosition.Y, minPosition.Z, 1);
shape.BoundingBoxNodes[4] = new Vector4(maxPosition.X, minPosition.Y, minPosition.Z, 1);
shape.BoundingBoxNodes[5] = new Vector4(maxPosition.X, minPosition.Y, maxPosition.Z, 1);
shape.BoundingBoxNodes[6] = new Vector4(maxPosition.X, maxPosition.Y, minPosition.Z, 1);
shape.BoundingBoxNodes[7] = maxPosition;
}
for (var j = 0; j < (gltfFile.Animations?.Length ?? 0); j++)
{
var gltfAnimation = gltfFile.Animations[j];
// Use MatrixNames for storing animation and articulation names.
// Here the MatrixNames are not bound to nodes (and matrices), but rather to the animation number.
shape.MatrixNames[j] = gltfAnimation.Name ?? "";
var animation = new GltfAnimation(shape.MatrixNames[j]);
for (var k = 0; k < gltfAnimation.Channels.Length; k++)
{
var gltfChannel = gltfAnimation.Channels[k];
if (gltfChannel.Target.Node == null) // then this is defined by an extension, which is not supported here.
continue;
var channel = new GltfAnimationChannel();
animation.Channels.Add(channel);
channel.Path = gltfChannel.Target.Path;
channel.TargetNode = (int)gltfChannel.Target.Node;
var sampler = gltfAnimation.Samplers[gltfChannel.Sampler];
var inputAccessor = gltfFile.Accessors[sampler.Input];
channel.TimeArray = new float[inputAccessor.Count];
channel.TimeMin = inputAccessor.Min[0];
channel.TimeMax = inputAccessor.Max[0];
var readInput = shape.GetNormalizedReader(inputAccessor.ComponentType);
using (var br = new BinaryReader(GetBufferView(inputAccessor, out _)))
{
for (var i = 0; i < inputAccessor.Count; i++)
channel.TimeArray[i] = readInput(br);
}
var outputAccessor = gltfFile.Accessors[sampler.Output];
switch (channel.Path)
{
case AnimationChannelTarget.PathEnum.rotation: channel.OutputQuaternion = new Quaternion[outputAccessor.Count]; break;
case AnimationChannelTarget.PathEnum.scale:
case AnimationChannelTarget.PathEnum.translation: channel.OutputVector3 = new Vector3[outputAccessor.Count]; break;
case AnimationChannelTarget.PathEnum.weights: channel.OutputWeights = new float[outputAccessor.Count]; break;
}
var readOutput = shape.GetNormalizedReader(outputAccessor.ComponentType);
using (var br = new BinaryReader(GetBufferView(outputAccessor, out _)))
{
for (var i = 0; i < outputAccessor.Count; i++)
switch (channel.Path)
{
case AnimationChannelTarget.PathEnum.rotation: channel.OutputQuaternion[i] = new Quaternion(readOutput(br), readOutput(br), readOutput(br), readOutput(br)); break;
case AnimationChannelTarget.PathEnum.scale:
case AnimationChannelTarget.PathEnum.translation: channel.OutputVector3[i] = new Vector3(readOutput(br), readOutput(br), readOutput(br)); break;
case AnimationChannelTarget.PathEnum.weights: channel.OutputWeights[i] = readOutput(br); morphWarning = true; break;
}
}
channel.Interpolation = sampler.Interpolation;
}
shape.GltfAnimations.Add(animation);
}
if (morphWarning)
Trace.TraceInformation($"glTF morphing animation is unsupported in file {gltfFileName}");
if (articulations != null)
{
if (shape.MatrixNames.Count < (gltfFile.Animations?.Length ?? 0) + articulations.Count)
shape.MatrixNames.AddRange(Enumerable.Repeat("", (gltfFile.Animations?.Length ?? 0) + articulations.Count - shape.MatrixNames.Count));
foreach (var nodeNumber in articulations.Keys)
{
var animation = shape.GltfAnimations.FirstOrDefault(a => a.Name == articulations[nodeNumber].name);
if (animation == null)
{
animation = new GltfAnimation(articulations[nodeNumber].name) { ExtrasWheelRadius = articulations[nodeNumber].radius };
shape.GltfAnimations.Add(animation);
shape.MatrixNames[shape.GltfAnimations.Count - 1] = articulations[nodeNumber].name ?? "";
}
animation.Channels.Add(new GltfAnimationChannel() { TargetNode = nodeNumber });
}
}
if (ConsistGenerator.GltfVisualTestRun)
{
// Assign the first four animations to Wipers [V], Item1Continuous [Shift+,], Item2Continuous [Shift+.] respectively,
// because these are the ones capable of playing a loop.
for (var i = 0; i < shape.GltfAnimations.Count; i++)
shape.MatrixNames[i] = TestControls[i % TestControls.Length];
}
}
}
internal Stream GetBufferView(AccessorSparseIndices accessor, out int? byteStride) => GetBufferView(accessor.BufferView, accessor.ByteOffset, out byteStride);
internal Stream GetBufferView(AccessorSparseValues accessor, out int? byteStride) => GetBufferView(accessor.BufferView, accessor.ByteOffset, out byteStride);
internal Stream GetBufferView(Accessor accessor, out int? byteStride) => GetBufferView(accessor.BufferView, accessor.ByteOffset, out byteStride);
internal Stream GetBufferView(int? bufferViewNumber, int accessorByteOffset, out int? byteStride)
{
byteStride = null;
if (bufferViewNumber == null)
return Stream.Null;
var bufferView = Gltf.BufferViews[(int)bufferViewNumber];
byteStride = bufferView.ByteStride;
if (!BinaryBuffers.TryGetValue(bufferView.Buffer, out var bytes))
BinaryBuffers.Add(bufferView.Buffer, bytes = glTFLoader.Interface.LoadBinaryBuffer(Gltf, bufferView.Buffer, GltfFileName));
var stream = new MemoryStream(bytes);
stream.Seek(bufferView.ByteOffset + accessorByteOffset, SeekOrigin.Begin);
return stream;
}
internal int GetSizeInBytes(Accessor accessor) => GetComponentNumber(accessor.Type) * GetCompenentSizeInBytes(accessor.ComponentType);
int GetComponentNumber(Accessor.TypeEnum type)
{
switch (type)
{
case Accessor.TypeEnum.SCALAR: return 1;
case Accessor.TypeEnum.VEC2: return 2;
case Accessor.TypeEnum.VEC3: return 3;
case Accessor.TypeEnum.VEC4:
case Accessor.TypeEnum.MAT2: return 4;
case Accessor.TypeEnum.MAT3: return 9;
case Accessor.TypeEnum.MAT4: return 16;
default: return 1;
}
}
int GetCompenentSizeInBytes(Accessor.ComponentTypeEnum componentType)
{
switch (componentType)
{
case Accessor.ComponentTypeEnum.BYTE:
case Accessor.ComponentTypeEnum.UNSIGNED_BYTE: return 1;
case Accessor.ComponentTypeEnum.SHORT:
case Accessor.ComponentTypeEnum.UNSIGNED_SHORT: return 2;
case Accessor.ComponentTypeEnum.UNSIGNED_INT:
case Accessor.ComponentTypeEnum.FLOAT:
default: return 4;
}
}
readonly List<float> BufferValues = new List<float>();
void ReadBuffer(Func<BinaryReader, float> read, BinaryReader br, Accessor.TypeEnum sourceType, int seek)
{
BufferValues.Clear();
for (var i = 0; i < GetComponentNumber(sourceType); i++)
BufferValues.Add(read(br));
br.BaseStream.Seek(seek, SeekOrigin.Current);
}
internal Vector2 ReadVector2(Func<BinaryReader, float> read, BinaryReader br, Accessor.TypeEnum sourceType, int seek)
{
ReadBuffer(read, br, sourceType, seek);
return new Vector2(BufferValues.ElementAtOrDefault(0), BufferValues.ElementAtOrDefault(1));
}
internal Vector3 ReadVector3(Func<BinaryReader, float> read, BinaryReader br, Accessor.TypeEnum sourceType, int seek)
{
ReadBuffer(read, br, sourceType, seek);
return new Vector3(BufferValues.ElementAtOrDefault(0), BufferValues.ElementAtOrDefault(1), BufferValues.ElementAtOrDefault(2));
}
internal Vector4 ReadVector4(Func<BinaryReader, float> read, BinaryReader br, Accessor.TypeEnum sourceType, int seek)
{
ReadBuffer(read, br, sourceType, seek);
return new Vector4(BufferValues.ElementAtOrDefault(0), BufferValues.ElementAtOrDefault(1), BufferValues.ElementAtOrDefault(2), BufferValues.ElementAtOrDefault(3));
}
internal Texture2D GetTexture(Gltf gltf, int? textureIndex, Texture2D defaultTexture)
{
if (textureIndex != null)
{
var texture = gltf.Textures[(int)textureIndex];
var source = texture?.Source;
var extensionFilter = StandardTextureExtensionFilter;
object extension = null;
if (texture?.Extensions?.TryGetValue("MSFT_texture_dds", out extension) ?? false)
{
var ext = Newtonsoft.Json.JsonConvert.DeserializeObject<MSFT_texture_dds>(extension.ToString());
source = ext?.Source ?? source;
extensionFilter = DdsTextureExtensionFilter;
}
if (source != null)
{
var image = gltf.Images[(int)source];
if (image.Uri != null)
{
var imagePath = source != null ? Path.Combine(GltfDir, Uri.UnescapeDataString(image.Uri)) : "";
if (File.Exists(imagePath))
{
// We refuse to load textures containing "../" in their path, because although it would be possible,
// it would break compatibility with the existing glTF viewers, including the Windows 3D Viewer,
// the VS Code glTF Tools and the reference Khronos glTF-Sample-Viewer.
var strippedImagePath = imagePath.Replace("../", "").Replace(@"..\", "").Replace("..", "");
if (File.Exists(strippedImagePath))
return Viewer.TextureManager.Get(strippedImagePath, defaultTexture, false, extensionFilter);
else
Trace.TraceWarning($"glTF: refusing to load texture {imagePath} in file {GltfFileName}, using \"../\" in the path is discouraged due to compatibility reasons.");
}
else
{
try
{
using (var stream = glTFLoader.Interface.OpenImageFile(gltf, (int)source, GltfFileName))
return Texture2D.FromStream(Viewer.GraphicsDevice, stream);
}
catch
{
Trace.TraceWarning($"glTF: missing texture {imagePath} in file {GltfFileName}");
}
}
}
else if (image.BufferView != null)
{
try
{
using (var stream = glTFLoader.Interface.OpenImageFile(gltf, (int)source, GltfFileName))
return Texture2D.FromStream(Viewer.GraphicsDevice, stream);
}
catch
{
Trace.TraceWarning($"glTF: missing image {image.BufferView} in file {GltfFileName}");
}
}
}
}
return defaultTexture;
}
internal TextureFilter GetTextureFilter(Sampler sampler)
{
if (sampler.MagFilter == Sampler.MagFilterEnum.LINEAR && sampler.MinFilter == Sampler.MinFilterEnum.LINEAR)
return TextureFilter.Linear;
if (sampler.MagFilter == Sampler.MagFilterEnum.LINEAR && sampler.MinFilter == Sampler.MinFilterEnum.LINEAR_MIPMAP_LINEAR)
return TextureFilter.Linear;
if (sampler.MagFilter == Sampler.MagFilterEnum.LINEAR && sampler.MinFilter == Sampler.MinFilterEnum.LINEAR_MIPMAP_NEAREST)
return TextureFilter.LinearMipPoint;
if (sampler.MagFilter == Sampler.MagFilterEnum.LINEAR && sampler.MinFilter == Sampler.MinFilterEnum.NEAREST_MIPMAP_LINEAR)
return TextureFilter.MinPointMagLinearMipLinear;
if (sampler.MagFilter == Sampler.MagFilterEnum.LINEAR && sampler.MinFilter == Sampler.MinFilterEnum.NEAREST_MIPMAP_NEAREST)
return TextureFilter.MinPointMagLinearMipPoint;
if (sampler.MagFilter == Sampler.MagFilterEnum.NEAREST && sampler.MinFilter == Sampler.MinFilterEnum.LINEAR_MIPMAP_LINEAR)
return TextureFilter.MinLinearMagPointMipLinear;
if (sampler.MagFilter == Sampler.MagFilterEnum.NEAREST && sampler.MinFilter == Sampler.MinFilterEnum.LINEAR_MIPMAP_NEAREST)
return TextureFilter.MinLinearMagPointMipPoint;
if (sampler.MagFilter == Sampler.MagFilterEnum.NEAREST && sampler.MinFilter == Sampler.MinFilterEnum.NEAREST_MIPMAP_LINEAR)
return TextureFilter.PointMipLinear;
if (sampler.MagFilter == Sampler.MagFilterEnum.NEAREST && sampler.MinFilter == Sampler.MinFilterEnum.NEAREST_MIPMAP_NEAREST)
return TextureFilter.Point;
if (sampler.MagFilter == Sampler.MagFilterEnum.NEAREST && sampler.MinFilter == Sampler.MinFilterEnum.NEAREST)
return TextureFilter.Point;
if (sampler.MagFilter == Sampler.MagFilterEnum.LINEAR && sampler.MinFilter == Sampler.MinFilterEnum.NEAREST)
return TextureFilter.MinPointMagLinearMipLinear;
if (sampler.MagFilter == Sampler.MagFilterEnum.NEAREST && sampler.MinFilter == Sampler.MinFilterEnum.LINEAR)
return TextureFilter.MinLinearMagPointMipLinear;
return TextureFilter.Linear;
}
internal (int, Texture2D, (TextureFilter, TextureAddressMode, TextureAddressMode)) GetTextureInfo(Gltf gltf, int? texCoord, int? index, Texture2D defaultTexture)
{
var texture = GetTexture(gltf, index, defaultTexture);
var sampler = gltf.Samplers?.ElementAtOrDefault(gltf.Textures?.ElementAtOrDefault(index ?? -1)?.Sampler ?? -1) ?? GltfSubObject.DefaultGltfSampler;
var samplerState = (GetTextureFilter(sampler), GetTextureAddressMode(sampler.WrapS), GetTextureAddressMode(sampler.WrapT));
return (texCoord ?? 0, texture, samplerState);
}
internal (int, Texture2D, (TextureFilter, TextureAddressMode, TextureAddressMode)) GetTextureInfo(Gltf gltf, TextureInfo textureInfo, Texture2D defaultTexture)
=> GetTextureInfo(gltf, textureInfo?.TexCoord, textureInfo?.Index, defaultTexture);
internal (int, Texture2D, (TextureFilter, TextureAddressMode, TextureAddressMode)) GetTextureInfo(Gltf gltf, MaterialNormalTextureInfo textureInfo, Texture2D defaultTexture)
=> GetTextureInfo(gltf, textureInfo?.TexCoord, textureInfo?.Index, defaultTexture);
internal (int, Texture2D, (TextureFilter, TextureAddressMode, TextureAddressMode)) GetTextureInfo(Gltf gltf, MaterialOcclusionTextureInfo textureInfo, Texture2D defaultTexture)
=> GetTextureInfo(gltf, textureInfo?.TexCoord, textureInfo?.Index, defaultTexture);
internal TextureAddressMode GetTextureAddressMode(Sampler.WrapTEnum wrapEnum) => GetTextureAddressMode((Sampler.WrapSEnum)wrapEnum);
internal TextureAddressMode GetTextureAddressMode(Sampler.WrapSEnum wrapEnum)
{
switch (wrapEnum)
{
case Sampler.WrapSEnum.REPEAT: return TextureAddressMode.Wrap;
case Sampler.WrapSEnum.CLAMP_TO_EDGE: return TextureAddressMode.Clamp;
case Sampler.WrapSEnum.MIRRORED_REPEAT: return TextureAddressMode.Mirror;
default: return TextureAddressMode.Wrap;
}
}
}
public class GltfSubObject : SubObject
{
public readonly Vector4 MinPosition;
public readonly Vector4 MaxPosition;
public readonly int HierarchyIndex;
public static readonly glTFLoader.Schema.Material DefaultGltfMaterial = new glTFLoader.Schema.Material
{
AlphaCutoff = 0.5f,
DoubleSided = false,
AlphaMode = glTFLoader.Schema.Material.AlphaModeEnum.OPAQUE,
EmissiveFactor = new[] {0f, 0f, 0f},
Name = nameof(DefaultGltfMaterial)
};
public static readonly glTFLoader.Schema.Sampler DefaultGltfSampler = new glTFLoader.Schema.Sampler
{
MagFilter = Sampler.MagFilterEnum.LINEAR,
MinFilter = Sampler.MinFilterEnum.LINEAR_MIPMAP_LINEAR,
WrapS = Sampler.WrapSEnum.REPEAT,
WrapT = Sampler.WrapTEnum.REPEAT,
Name = nameof(DefaultGltfSampler)
};
public GltfSubObject(KHR_lights_punctual light, int hierarchyIndex, int[] hierarchy, Gltf gltfFile, GltfShape shape, GltfDistanceLevel distanceLevel)
{
ShapePrimitives = new[] { new GltfPrimitive(light, gltfFile, distanceLevel, hierarchyIndex, hierarchy) };
}
public GltfSubObject(MeshPrimitive meshPrimitive, string name, int hierarchyIndex, int[] hierarchy, Helpers.TextureFlags textureFlags, Gltf gltfFile, GltfShape shape, GltfDistanceLevel distanceLevel, Skin skin)
{
var material = meshPrimitive.Material == null ? DefaultGltfMaterial : gltfFile.Materials[(int)meshPrimitive.Material];
var options = SceneryMaterialOptions.None;
if (!material.Extensions?.ContainsKey("KHR_materials_unlit") ?? true)
options |= SceneryMaterialOptions.Diffuse;
if (skin != null)
{
options |= SceneryMaterialOptions.PbrHasSkin;
shape.SkeletonRootNode = skin.Skeleton ?? 0;
}
if (!shape.MsfsFlavoured && distanceLevel.Matrices[hierarchyIndex].Determinant() > 0)
// This is according to the glTF spec
options |= SceneryMaterialOptions.PbrCullClockWise;
else if (shape.MsfsFlavoured && distanceLevel.Matrices[hierarchyIndex].Determinant() < 0)
// Msfs seems to be using this reversed
options |= SceneryMaterialOptions.PbrCullClockWise;
var referenceAlpha = 0f;
var doubleSided = material.DoubleSided;
switch (material.AlphaMode)
{
case glTFLoader.Schema.Material.AlphaModeEnum.BLEND: options |= SceneryMaterialOptions.AlphaBlendingBlend; break;
case glTFLoader.Schema.Material.AlphaModeEnum.MASK: options |= SceneryMaterialOptions.AlphaTest; referenceAlpha = material.AlphaCutoff; break;
case glTFLoader.Schema.Material.AlphaModeEnum.OPAQUE:
default: break;
}
Vector4 texCoords1 = Vector4.Zero; // x: baseColor, y: roughness-metallic, z: normal, w: emissive
Vector4 texCoords2 = Vector4.Zero; // x: clearcoat, y: clearcoat-roughness, z: clearcoat-normal, w: occlusion
MaterialNormalTextureInfo msftNormalInfo = null;
TextureInfo msftOrmInfo = null;
TextureInfo msftRmoInfo = null;
object extension = null;
if (material.Extensions?.TryGetValue("MSFT_packing_normalRoughnessMetallic", out extension) ?? false)
msftNormalInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<MSFT_packing_normalRoughnessMetallic>(extension.ToString())?.NormalRoughnessMetallicTexture;
else if (material.Extensions?.TryGetValue("MSFT_packing_occlusionRoughnessMetallic", out extension) ?? false)
{
var ext = Newtonsoft.Json.JsonConvert.DeserializeObject<MSFT_packing_occlusionRoughnessMetallic>(extension.ToString());
msftOrmInfo = ext?.OcclusionRoughnessMetallicTexture;
msftRmoInfo = ext?.RoughnessMetallicOcclusionTexture;
msftNormalInfo = ext?.NormalTexture;
}
// 0: occlusion (R), roughnessMetallic (GB) together, normal (RGB) separate, this is the standard
// 1: roughnessMetallicOcclusion together, normal (RGB) separate
// 2: normalRoughnessMetallic (RG+B+A) together, occlusion (R) separate
// 3: occlusionRoughnessMetallic together, normal (RGB) separate
// 4: roughnessMetallicOcclusion together, normal (RG) 2 channel separate
// 5: occlusionRoughnessMetallic together, normal (RG) 2 channel separate
var texturePacking =
msftOrmInfo != null ? msftNormalInfo != null ? 5 : 3 :
msftRmoInfo != null ? msftNormalInfo != null ? 4 : 1 :
msftNormalInfo != null ? 2 : 0;
// baseColor texture is 8 bit sRGB + A. Needs decoding to linear in the shader.
// metallicRoughness texture G = roughness, B = metalness, linear, may be > 8 bit
// normal texture is RGB linear, B should be >= 0.5. All channels need mapping from the [0.0..1.0] to the [-1.0..1.0] range, = sampledValue * 2.0 - 1.0
// occlusion texture R channel only, = 1.0 + strength * (sampledValue - 1.0)
// emissive texture 8 bit sRGB. Needs decoding to linear in the shader.
// clearcoat texture R channel only
// clearcoatRoughness texture G channel only
Texture2D baseColorTexture = null, metallicRoughnessTexture = null, normalTexture = null, occlusionTexture = null, emissiveTexture = null, clearcoatTexture = null, clearcoatRoughnessTexture = null, clearcoatNormalTexture = null;
(TextureFilter, TextureAddressMode, TextureAddressMode) baseColorSamplerState = default, metallicRoughnessSamplerState = default, normalSamplerState = default, occlusionSamplerState = default, emissiveSamplerState = default, clearcoatSamplerState = default, clearcoatRoughnessSamplerState = default, clearcoatNormalSamplerState = default;
KHR_materials_clearcoat clearcoat = null;
if (material.Extensions?.TryGetValue("KHR_materials_clearcoat", out extension) ?? false)
clearcoat = Newtonsoft.Json.JsonConvert.DeserializeObject<KHR_materials_clearcoat>(extension.ToString());
(texCoords1.X, baseColorTexture, baseColorSamplerState) = distanceLevel.GetTextureInfo(gltfFile, material.PbrMetallicRoughness?.BaseColorTexture, SharedMaterialManager.WhiteTexture);
(texCoords1.Y, metallicRoughnessTexture, metallicRoughnessSamplerState) = distanceLevel.GetTextureInfo(gltfFile, msftRmoInfo ?? msftOrmInfo ?? material.PbrMetallicRoughness?.MetallicRoughnessTexture, SharedMaterialManager.WhiteTexture);
(texCoords1.Z, normalTexture, normalSamplerState) = distanceLevel.GetTextureInfo(gltfFile, msftNormalInfo ?? material.NormalTexture, SharedMaterialManager.WhiteTexture);
(texCoords1.W, emissiveTexture, emissiveSamplerState) = distanceLevel.GetTextureInfo(gltfFile, material.EmissiveTexture, SharedMaterialManager.WhiteTexture);
(texCoords2.W, occlusionTexture, occlusionSamplerState) = msftOrmInfo != null
? distanceLevel.GetTextureInfo(gltfFile, msftOrmInfo, SharedMaterialManager.WhiteTexture)
: distanceLevel.GetTextureInfo(gltfFile, material.OcclusionTexture, SharedMaterialManager.WhiteTexture);
(texCoords2.X, clearcoatTexture, clearcoatSamplerState) = distanceLevel.GetTextureInfo(gltfFile, clearcoat?.ClearcoatTexture, SharedMaterialManager.WhiteTexture);
(texCoords2.Y, clearcoatRoughnessTexture, clearcoatRoughnessSamplerState) = distanceLevel.GetTextureInfo(gltfFile, clearcoat?.ClearcoatRoughnessTexture, SharedMaterialManager.WhiteTexture);
(texCoords2.Z, clearcoatNormalTexture, clearcoatNormalSamplerState) = distanceLevel.GetTextureInfo(gltfFile, clearcoat?.ClearcoatNormalTexture, SharedMaterialManager.WhiteTexture);
var baseColorFactor = material.PbrMetallicRoughness?.BaseColorFactor ?? new[] { 1f, 1f, 1f, 1f };
var baseColorFactorVector = new Vector4(baseColorFactor[0], baseColorFactor[1], baseColorFactor[2], baseColorFactor[3]);
var metallicFactor = material.PbrMetallicRoughness?.MetallicFactor ?? 1f;
var roughtnessFactor = material.PbrMetallicRoughness?.RoughnessFactor ?? 1f;
var normalScale = material.NormalTexture?.Scale ?? 0; // Must be 0 only if the textureInfo is missing, otherwise it must have the default value 1.
var occlusionStrength = material.OcclusionTexture?.Strength ?? 0; // Must be 0 only if the textureInfo is missing, otherwise it must have the default value 1.
var emissiveFactor = material.EmissiveFactor ?? new[] { 0f, 0f, 0f };
var emissiveFactorVector = new Vector3(emissiveFactor[0], emissiveFactor[1], emissiveFactor[2]);
var clearcoatFactor = clearcoat?.ClearcoatFactor ?? 0;
var clearcoatRoughnessFactor = clearcoat?.ClearcoatRoughnessFactor ?? 0;
var clearcoatNormalScale = clearcoat?.ClearcoatNormalTexture?.Scale ?? 1;
switch (baseColorSamplerState.Item2)
{
case TextureAddressMode.Wrap: options |= SceneryMaterialOptions.TextureAddressModeWrap; break;
case TextureAddressMode.Clamp: options |= SceneryMaterialOptions.TextureAddressModeClamp; break;
case TextureAddressMode.Mirror: options |= SceneryMaterialOptions.TextureAddressModeMirror; break;
}
var indexBufferSet = new GltfIndexBufferSet();
ushort[] indexData = null;
if (meshPrimitive.Indices != null)
{
var accessor = gltfFile.Accessors[(int)meshPrimitive.Indices];
indexData = new ushort[accessor.Count];
var read = GetIntegerReader(accessor.ComponentType);
using (var br = new BinaryReader(distanceLevel.GetBufferView(accessor, out _)))
{
for (var i = 0; i < indexData.Length; i++)
indexData[i] = read(br);
}
if (accessor.Sparse != null)
{
var readI = GetIntegerReader(accessor.Sparse.Indices.ComponentType);
using (var bri = new BinaryReader(distanceLevel.GetBufferView(accessor.Sparse.Indices, out _)))
using (var br = new BinaryReader(distanceLevel.GetBufferView(accessor.Sparse.Values, out _)))
{
for (var i = 0; i < accessor.Sparse.Count; i++)
indexData[readI(bri)] = read(br);
}
}
indexBufferSet.IndexBuffer = new IndexBuffer(shape.Viewer.GraphicsDevice, typeof(ushort), indexData.Length, BufferUsage.None);
indexBufferSet.IndexBuffer.SetData(indexData);
indexBufferSet.IndexBuffer.Name = name;
options |= SceneryMaterialOptions.PbrHasIndices;
}
var vertexAttributes = new List<VertexBufferBinding>();
VertexPosition[] vertexPositions = null;
VertexNormal[] vertexNormals = null;
VertexTextureDiffuse[] vertexTextureUvs = null;
VertexBuffer vertexBufferTextureUvs = null;
if (meshPrimitive.Attributes.TryGetValue("POSITION", out var accessorNumber))
{
if (!shape.VertexBuffers.TryGetValue(accessorNumber, out var vertexBufferBinding) || meshPrimitive.Attributes.ContainsKey("COLOR_0"))
{
// The condition COLOR_0 is here to allow the mesh to go through the normalmap pipeline with calculating tangents, where the positions are needed anyways.
var accessor = gltfFile.Accessors[accessorNumber];
var componentSizeInBytes = distanceLevel.GetSizeInBytes(accessor);
vertexPositions = new VertexPosition[accessor.Count];
var read = shape.GetNormalizedReader(accessor.ComponentType);
using (var br = new BinaryReader(distanceLevel.GetBufferView(accessor, out var byteStride)))
{
var seek = byteStride != null ? (int)byteStride - componentSizeInBytes : 0;
for (var i = 0; i < vertexPositions.Length; i++)
vertexPositions[i] = new VertexPosition(distanceLevel.ReadVector3(read, br, accessor.Type, seek));
}
if (accessor.Sparse != null)
{
var readI = GetIntegerReader(accessor.Sparse.Indices.ComponentType);
using (var bri = new BinaryReader(distanceLevel.GetBufferView(accessor.Sparse.Indices, out _)))
using (var br = new BinaryReader(distanceLevel.GetBufferView(accessor.Sparse.Values, out var byteStride)))
{
var seek = byteStride != null ? (int)byteStride - componentSizeInBytes : 0;
for (var i = 0; i < accessor.Sparse.Count; i++)
vertexPositions[readI(bri)] = new VertexPosition(distanceLevel.ReadVector3(read, br, accessor.Type, seek));
}
}
if (vertexBufferBinding.VertexBuffer == null)
{
var vertexBuffer = new VertexBuffer(shape.Viewer.GraphicsDevice, typeof(VertexPosition), vertexPositions.Length, BufferUsage.None);
vertexBuffer.SetData(vertexPositions);
vertexBuffer.Name = "POSITION";
vertexBufferBinding = new VertexBufferBinding(vertexBuffer);
}
if (!shape.VertexBuffers.ContainsKey(accessorNumber))
shape.VertexBuffers.Add(accessorNumber, vertexBufferBinding);
MinPosition = new Vector4(accessor.Min[0], accessor.Min[1], accessor.Min[2], 1);
MaxPosition = new Vector4(accessor.Max[0], accessor.Max[1], accessor.Max[2], 1);
HierarchyIndex = hierarchyIndex;
}
vertexAttributes.Add(vertexBufferBinding);
}
else
{
throw new NotImplementedException("One of the glTF mesh primitives has no positions.");
}
if (meshPrimitive.Attributes.TryGetValue("NORMAL", out accessorNumber))
{
if (!shape.VertexBuffers.TryGetValue(accessorNumber, out var vertexBufferBinding))
{
var accessor = gltfFile.Accessors[accessorNumber];
var componentSizeInBytes = distanceLevel.GetSizeInBytes(accessor);
vertexNormals = new VertexNormal[accessor.Count];
var read = shape.GetNormalizedReader(accessor.ComponentType);
using (var br = new BinaryReader(distanceLevel.GetBufferView(accessor, out var byteStride)))
{
var seek = byteStride != null ? (int)byteStride - componentSizeInBytes : 0;
for (var i = 0; i < vertexNormals.Length; i++)
vertexNormals[i] = new VertexNormal(distanceLevel.ReadVector3(read, br, accessor.Type, seek));
}
if (accessor.Sparse != null)
{
var readI = GetIntegerReader(accessor.Sparse.Indices.ComponentType);
using (var bri = new BinaryReader(distanceLevel.GetBufferView(accessor.Sparse.Indices, out _)))
using (var br = new BinaryReader(distanceLevel.GetBufferView(accessor.Sparse.Values, out var byteStride)))
{
var seek = byteStride != null ? (int)byteStride - componentSizeInBytes : 0;