@playcanvas/supersplat-viewer 1.14.0 → 1.14.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/public/index.js CHANGED
@@ -4448,6 +4448,7 @@ const getPixelFormatArrayType = (format)=>{
4448
4448
  };
4449
4449
  const PRIMITIVE_POINTS = 0;
4450
4450
  const PRIMITIVE_LINES = 1;
4451
+ const PRIMITIVE_LINELOOP = 2;
4451
4452
  const PRIMITIVE_LINESTRIP = 3;
4452
4453
  const PRIMITIVE_TRIANGLES = 4;
4453
4454
  const PRIMITIVE_TRISTRIP = 5;
@@ -25376,6 +25377,333 @@ class MorphInstance {
25376
25377
  }
25377
25378
  }
25378
25379
 
25380
+ class Model {
25381
+ getGraph() {
25382
+ return this.graph;
25383
+ }
25384
+ setGraph(graph) {
25385
+ this.graph = graph;
25386
+ }
25387
+ getCameras() {
25388
+ return this.cameras;
25389
+ }
25390
+ setCameras(cameras) {
25391
+ this.cameras = cameras;
25392
+ }
25393
+ getLights() {
25394
+ return this.lights;
25395
+ }
25396
+ setLights(lights) {
25397
+ this.lights = lights;
25398
+ }
25399
+ getMaterials() {
25400
+ const materials = [];
25401
+ for(let i = 0; i < this.meshInstances.length; i++){
25402
+ const meshInstance = this.meshInstances[i];
25403
+ if (materials.indexOf(meshInstance.material) === -1) {
25404
+ materials.push(meshInstance.material);
25405
+ }
25406
+ }
25407
+ return materials;
25408
+ }
25409
+ clone() {
25410
+ const srcNodes = [];
25411
+ const cloneNodes = [];
25412
+ const _duplicate = function(node) {
25413
+ const newNode = node.clone();
25414
+ srcNodes.push(node);
25415
+ cloneNodes.push(newNode);
25416
+ for(let idx = 0; idx < node._children.length; idx++){
25417
+ newNode.addChild(_duplicate(node._children[idx]));
25418
+ }
25419
+ return newNode;
25420
+ };
25421
+ const cloneGraph = _duplicate(this.graph);
25422
+ const cloneMeshInstances = [];
25423
+ const cloneSkinInstances = [];
25424
+ const cloneMorphInstances = [];
25425
+ for(let i = 0; i < this.skinInstances.length; i++){
25426
+ const skin = this.skinInstances[i].skin;
25427
+ const cloneSkinInstance = new SkinInstance(skin);
25428
+ const bones = [];
25429
+ for(let j = 0; j < skin.boneNames.length; j++){
25430
+ const boneName = skin.boneNames[j];
25431
+ const bone = cloneGraph.findByName(boneName);
25432
+ bones.push(bone);
25433
+ }
25434
+ cloneSkinInstance.bones = bones;
25435
+ cloneSkinInstances.push(cloneSkinInstance);
25436
+ }
25437
+ for(let i = 0; i < this.morphInstances.length; i++){
25438
+ const morph = this.morphInstances[i].morph;
25439
+ const cloneMorphInstance = new MorphInstance(morph);
25440
+ cloneMorphInstances.push(cloneMorphInstance);
25441
+ }
25442
+ for(let i = 0; i < this.meshInstances.length; i++){
25443
+ const meshInstance = this.meshInstances[i];
25444
+ const nodeIndex = srcNodes.indexOf(meshInstance.node);
25445
+ const cloneMeshInstance = new MeshInstance(meshInstance.mesh, meshInstance.material, cloneNodes[nodeIndex]);
25446
+ if (meshInstance.skinInstance) {
25447
+ const skinInstanceIndex = this.skinInstances.indexOf(meshInstance.skinInstance);
25448
+ cloneMeshInstance.skinInstance = cloneSkinInstances[skinInstanceIndex];
25449
+ }
25450
+ if (meshInstance.morphInstance) {
25451
+ const morphInstanceIndex = this.morphInstances.indexOf(meshInstance.morphInstance);
25452
+ cloneMeshInstance.morphInstance = cloneMorphInstances[morphInstanceIndex];
25453
+ }
25454
+ cloneMeshInstances.push(cloneMeshInstance);
25455
+ }
25456
+ const clone = new Model();
25457
+ clone.graph = cloneGraph;
25458
+ clone.meshInstances = cloneMeshInstances;
25459
+ clone.skinInstances = cloneSkinInstances;
25460
+ clone.morphInstances = cloneMorphInstances;
25461
+ clone.getGraph().syncHierarchy();
25462
+ return clone;
25463
+ }
25464
+ destroy() {
25465
+ const meshInstances = this.meshInstances;
25466
+ for(let i = 0; i < meshInstances.length; i++){
25467
+ meshInstances[i].destroy();
25468
+ }
25469
+ this.meshInstances.length = 0;
25470
+ }
25471
+ generateWireframe() {
25472
+ MeshInstance._prepareRenderStyleForArray(this.meshInstances, RENDERSTYLE_WIREFRAME);
25473
+ }
25474
+ constructor(){
25475
+ this.graph = null;
25476
+ this.meshInstances = [];
25477
+ this.skinInstances = [];
25478
+ this.morphInstances = [];
25479
+ this.cameras = [];
25480
+ this.lights = [];
25481
+ this._shadersVersion = 0;
25482
+ this._immutable = false;
25483
+ }
25484
+ }
25485
+
25486
+ class Morph extends RefCountedObject {
25487
+ destroy() {
25488
+ this.vertexBufferIds?.destroy();
25489
+ this.vertexBufferIds = null;
25490
+ this.targetsTexturePositions?.destroy();
25491
+ this.targetsTexturePositions = null;
25492
+ this.targetsTextureNormals?.destroy();
25493
+ this.targetsTextureNormals = null;
25494
+ }
25495
+ get aabb() {
25496
+ if (!this._aabb) {
25497
+ const min = new Vec3();
25498
+ const max = new Vec3();
25499
+ for(let i = 0; i < this._targets.length; i++){
25500
+ const targetAabb = this._targets[i].aabb;
25501
+ min.min(targetAabb.getMin());
25502
+ max.max(targetAabb.getMax());
25503
+ }
25504
+ this._aabb = new BoundingBox();
25505
+ this._aabb.setMinMax(min, max);
25506
+ }
25507
+ return this._aabb;
25508
+ }
25509
+ get morphPositions() {
25510
+ return this._morphPositions;
25511
+ }
25512
+ get morphNormals() {
25513
+ return this._morphNormals;
25514
+ }
25515
+ _init() {
25516
+ this._initTextureBased();
25517
+ for(let i = 0; i < this._targets.length; i++){
25518
+ this._targets[i]._postInit();
25519
+ }
25520
+ }
25521
+ _findSparseSet(deltaArrays, ids, usedDataIndices) {
25522
+ let freeIndex = 1;
25523
+ const dataCount = deltaArrays[0].length;
25524
+ for(let v = 0; v < dataCount; v += 3){
25525
+ let vertexUsed = false;
25526
+ for(let i = 0; i < deltaArrays.length; i++){
25527
+ const data = deltaArrays[i];
25528
+ if (data[v] !== 0 || data[v + 1] !== 0 || data[v + 2] !== 0) {
25529
+ vertexUsed = true;
25530
+ break;
25531
+ }
25532
+ }
25533
+ if (vertexUsed) {
25534
+ ids.push(freeIndex);
25535
+ usedDataIndices.push(v / 3);
25536
+ freeIndex++;
25537
+ } else {
25538
+ ids.push(0);
25539
+ }
25540
+ }
25541
+ return freeIndex;
25542
+ }
25543
+ _initTextureBased() {
25544
+ const deltaArrays = [], deltaInfos = [];
25545
+ const targets = this._targets;
25546
+ for(let i = 0; i < targets.length; i++){
25547
+ const target = targets[i];
25548
+ if (target.options.deltaPositions) {
25549
+ deltaArrays.push(target.options.deltaPositions);
25550
+ deltaInfos.push(true);
25551
+ }
25552
+ if (target.options.deltaNormals) {
25553
+ deltaArrays.push(target.options.deltaNormals);
25554
+ deltaInfos.push(false);
25555
+ }
25556
+ }
25557
+ const ids = [], usedDataIndices = [];
25558
+ const freeIndex = this._findSparseSet(deltaArrays, ids, usedDataIndices);
25559
+ const maxTextureSize = this.device.maxTextureSize;
25560
+ let morphTextureWidth = Math.ceil(Math.sqrt(freeIndex));
25561
+ morphTextureWidth = Math.min(morphTextureWidth, maxTextureSize);
25562
+ const morphTextureHeight = Math.ceil(freeIndex / morphTextureWidth);
25563
+ if (morphTextureHeight > maxTextureSize) {
25564
+ return;
25565
+ }
25566
+ this.morphTextureWidth = morphTextureWidth;
25567
+ this.morphTextureHeight = morphTextureHeight;
25568
+ let halfFloat = false;
25569
+ const float2Half = FloatPacking.float2Half;
25570
+ if (this._textureFormat === PIXELFORMAT_RGBA16F) {
25571
+ halfFloat = true;
25572
+ }
25573
+ const texturesDataPositions = [];
25574
+ const texturesDataNormals = [];
25575
+ const textureDataSize = morphTextureWidth * morphTextureHeight * 4;
25576
+ for(let i = 0; i < deltaArrays.length; i++){
25577
+ const data = deltaArrays[i];
25578
+ const textureData = this._textureFormat === PIXELFORMAT_RGBA16F ? new Uint16Array(textureDataSize) : new Float32Array(textureDataSize);
25579
+ (deltaInfos[i] ? texturesDataPositions : texturesDataNormals).push(textureData);
25580
+ if (halfFloat) {
25581
+ for(let v = 0; v < usedDataIndices.length; v++){
25582
+ const index = usedDataIndices[v] * 3;
25583
+ const dstIndex = v * 4 + 4;
25584
+ textureData[dstIndex] = float2Half(data[index]);
25585
+ textureData[dstIndex + 1] = float2Half(data[index + 1]);
25586
+ textureData[dstIndex + 2] = float2Half(data[index + 2]);
25587
+ }
25588
+ } else {
25589
+ for(let v = 0; v < usedDataIndices.length; v++){
25590
+ const index = usedDataIndices[v] * 3;
25591
+ const dstIndex = v * 4 + 4;
25592
+ textureData[dstIndex] = data[index];
25593
+ textureData[dstIndex + 1] = data[index + 1];
25594
+ textureData[dstIndex + 2] = data[index + 2];
25595
+ }
25596
+ }
25597
+ }
25598
+ if (texturesDataPositions.length > 0) {
25599
+ this.targetsTexturePositions = this._createTexture('MorphPositionsTexture', this._textureFormat, targets.length, [
25600
+ texturesDataPositions
25601
+ ]);
25602
+ }
25603
+ if (texturesDataNormals.length > 0) {
25604
+ this.targetsTextureNormals = this._createTexture('MorphNormalsTexture', this._textureFormat, targets.length, [
25605
+ texturesDataNormals
25606
+ ]);
25607
+ }
25608
+ const formatDesc = [
25609
+ {
25610
+ semantic: SEMANTIC_ATTR15,
25611
+ components: 1,
25612
+ type: TYPE_UINT32,
25613
+ asInt: true
25614
+ }
25615
+ ];
25616
+ this.vertexBufferIds = new VertexBuffer(this.device, new VertexFormat(this.device, formatDesc, ids.length), ids.length, {
25617
+ data: new Uint32Array(ids)
25618
+ });
25619
+ return true;
25620
+ }
25621
+ get targets() {
25622
+ return this._targets;
25623
+ }
25624
+ _updateMorphFlags() {
25625
+ this._morphPositions = false;
25626
+ this._morphNormals = false;
25627
+ for(let i = 0; i < this._targets.length; i++){
25628
+ const target = this._targets[i];
25629
+ if (target.morphPositions) {
25630
+ this._morphPositions = true;
25631
+ }
25632
+ if (target.morphNormals) {
25633
+ this._morphNormals = true;
25634
+ }
25635
+ }
25636
+ }
25637
+ _createTexture(name, format, arrayLength, levels) {
25638
+ return new Texture(this.device, {
25639
+ levels: levels,
25640
+ arrayLength: arrayLength,
25641
+ width: this.morphTextureWidth,
25642
+ height: this.morphTextureHeight,
25643
+ format: format,
25644
+ cubemap: false,
25645
+ mipmaps: false,
25646
+ minFilter: FILTER_NEAREST,
25647
+ magFilter: FILTER_NEAREST,
25648
+ addressU: ADDRESS_CLAMP_TO_EDGE,
25649
+ addressV: ADDRESS_CLAMP_TO_EDGE,
25650
+ name: name
25651
+ });
25652
+ }
25653
+ constructor(targets, graphicsDevice, { preferHighPrecision = false } = {}){
25654
+ super();
25655
+ this.device = graphicsDevice;
25656
+ const device = graphicsDevice;
25657
+ this.preferHighPrecision = preferHighPrecision;
25658
+ this._targets = targets.slice();
25659
+ const renderableHalf = device.textureHalfFloatRenderable ? PIXELFORMAT_RGBA16F : undefined;
25660
+ const renderableFloat = device.textureFloatRenderable ? PIXELFORMAT_RGBA32F : undefined;
25661
+ this._renderTextureFormat = this.preferHighPrecision ? renderableFloat ?? renderableHalf : renderableHalf ?? renderableFloat;
25662
+ this._renderTextureFormat = this._renderTextureFormat ?? PIXELFORMAT_RGBA16U;
25663
+ this.intRenderFormat = isIntegerPixelFormat(this._renderTextureFormat);
25664
+ this._textureFormat = this.preferHighPrecision ? PIXELFORMAT_RGBA32F : PIXELFORMAT_RGBA16F;
25665
+ this._init();
25666
+ this._updateMorphFlags();
25667
+ }
25668
+ }
25669
+
25670
+ class MorphTarget {
25671
+ get name() {
25672
+ return this._name;
25673
+ }
25674
+ get defaultWeight() {
25675
+ return this._defaultWeight;
25676
+ }
25677
+ get aabb() {
25678
+ if (!this._aabb) {
25679
+ this._aabb = new BoundingBox();
25680
+ if (this.deltaPositions) {
25681
+ this._aabb.compute(this.deltaPositions);
25682
+ }
25683
+ }
25684
+ return this._aabb;
25685
+ }
25686
+ clone() {
25687
+ return new MorphTarget(this.options);
25688
+ }
25689
+ _postInit() {
25690
+ if (!this.options.preserveData) {
25691
+ this.options = null;
25692
+ }
25693
+ this.used = true;
25694
+ }
25695
+ constructor(options){
25696
+ this.used = false;
25697
+ this.options = options;
25698
+ this._name = options.name;
25699
+ this._defaultWeight = options.defaultWeight || 0;
25700
+ this._aabb = options.aabb;
25701
+ this.deltaPositions = options.deltaPositions;
25702
+ this.morphPositions = !!options.deltaPositions;
25703
+ this.morphNormals = !!options.deltaNormals;
25704
+ }
25705
+ }
25706
+
25379
25707
  class ShaderGeneratorShader extends ShaderGenerator {
25380
25708
  generateKey(options) {
25381
25709
  const desc = options.shaderDesc;
@@ -27657,6 +27985,14 @@ Scene.EVENT_POSTRENDER_LAYER = 'postrender:layer';
27657
27985
  Scene.EVENT_PRECULL = 'precull';
27658
27986
  Scene.EVENT_POSTCULL = 'postcull';
27659
27987
 
27988
+ class Skin {
27989
+ constructor(graphicsDevice, ibp, boneNames){
27990
+ this.device = graphicsDevice;
27991
+ this.inverseBindPose = ibp;
27992
+ this.boneNames = boneNames;
27993
+ }
27994
+ }
27995
+
27660
27996
  const prefixSumSource = `
27661
27997
  @group(0) @binding(0) var<storage, read_write> items: array<u32>;
27662
27998
  @group(0) @binding(1) var<storage, read_write> blockSums: array<u32>;
@@ -47580,6 +47916,72 @@ function convertValue(value, type) {
47580
47916
  }
47581
47917
  }
47582
47918
 
47919
+ const INTERPOLATION_STEP = 0;
47920
+ const INTERPOLATION_LINEAR = 1;
47921
+ const INTERPOLATION_CUBIC = 2;
47922
+
47923
+ class AnimEvents {
47924
+ get events() {
47925
+ return this._events;
47926
+ }
47927
+ constructor(events){
47928
+ this._events = [
47929
+ ...events
47930
+ ];
47931
+ this._events.sort((a, b)=>a.time - b.time);
47932
+ }
47933
+ }
47934
+
47935
+ class AnimTrack {
47936
+ get name() {
47937
+ return this._name;
47938
+ }
47939
+ get duration() {
47940
+ return this._duration;
47941
+ }
47942
+ get inputs() {
47943
+ return this._inputs;
47944
+ }
47945
+ get outputs() {
47946
+ return this._outputs;
47947
+ }
47948
+ get curves() {
47949
+ return this._curves;
47950
+ }
47951
+ set events(animEvents) {
47952
+ this._animEvents = animEvents;
47953
+ }
47954
+ get events() {
47955
+ return this._animEvents.events;
47956
+ }
47957
+ eval(time, snapshot) {
47958
+ snapshot._time = time;
47959
+ const inputs = this._inputs;
47960
+ const outputs = this._outputs;
47961
+ const curves = this._curves;
47962
+ const cache = snapshot._cache;
47963
+ const results = snapshot._results;
47964
+ for(let i = 0; i < inputs.length; ++i){
47965
+ cache[i].update(time, inputs[i]._data);
47966
+ }
47967
+ for(let i = 0; i < curves.length; ++i){
47968
+ const curve = curves[i];
47969
+ const output = outputs[curve._output];
47970
+ const result = results[i];
47971
+ cache[curve._input].eval(result, curve._interpolation, output);
47972
+ }
47973
+ }
47974
+ constructor(name, duration, inputs, outputs, curves, animEvents = new AnimEvents([])){
47975
+ this._name = name;
47976
+ this._duration = duration;
47977
+ this._inputs = inputs;
47978
+ this._outputs = outputs;
47979
+ this._curves = curves;
47980
+ this._animEvents = animEvents;
47981
+ }
47982
+ }
47983
+ AnimTrack.EMPTY = Object.freeze(new AnimTrack('empty', Number.MAX_VALUE, [], [], []));
47984
+
47583
47985
  class PrimitivesCache {
47584
47986
  destroy(device) {
47585
47987
  this.map.forEach((primData)=>primData.mesh.destroy());
@@ -56023,6 +56425,2563 @@ GSplatComponentSystem.EVENT_MATERIALCREATED = 'material:created';
56023
56425
  GSplatComponentSystem.EVENT_FRAMEREADY = 'frame:ready';
56024
56426
  Component._buildAccessors(GSplatComponent.prototype, _schema);
56025
56427
 
56428
+ class Render extends EventHandler {
56429
+ set meshes(value) {
56430
+ this.decRefMeshes();
56431
+ this._meshes = value;
56432
+ this.incRefMeshes();
56433
+ this.fire('set:meshes', value);
56434
+ }
56435
+ get meshes() {
56436
+ return this._meshes;
56437
+ }
56438
+ destroy() {
56439
+ this.meshes = null;
56440
+ }
56441
+ decRefMeshes() {
56442
+ this._meshes?.forEach((mesh, index)=>{
56443
+ if (mesh) {
56444
+ mesh.decRefCount();
56445
+ if (mesh.refCount < 1) {
56446
+ mesh.destroy();
56447
+ this._meshes[index] = null;
56448
+ }
56449
+ }
56450
+ });
56451
+ }
56452
+ incRefMeshes() {
56453
+ this._meshes?.forEach((mesh)=>{
56454
+ mesh?.incRefCount();
56455
+ });
56456
+ }
56457
+ constructor(...args){
56458
+ super(...args), this._meshes = null;
56459
+ }
56460
+ }
56461
+ Render.EVENT_SETMESHES = 'set:meshes';
56462
+
56463
+ class AnimCurve {
56464
+ get paths() {
56465
+ return this._paths;
56466
+ }
56467
+ get input() {
56468
+ return this._input;
56469
+ }
56470
+ get output() {
56471
+ return this._output;
56472
+ }
56473
+ get interpolation() {
56474
+ return this._interpolation;
56475
+ }
56476
+ constructor(paths, input, output, interpolation){
56477
+ this._paths = paths;
56478
+ this._input = input;
56479
+ this._output = output;
56480
+ this._interpolation = interpolation;
56481
+ }
56482
+ }
56483
+
56484
+ class AnimData {
56485
+ get components() {
56486
+ return this._components;
56487
+ }
56488
+ get data() {
56489
+ return this._data;
56490
+ }
56491
+ constructor(components, data){
56492
+ this._components = components;
56493
+ this._data = data;
56494
+ }
56495
+ }
56496
+
56497
+ function DracoWorker(jsUrl, wasmUrl) {
56498
+ let draco;
56499
+ const POSITION_ATTRIBUTE = 0;
56500
+ const NORMAL_ATTRIBUTE = 1;
56501
+ const wrap = (typedArray, dataType)=>{
56502
+ switch(dataType){
56503
+ case draco.DT_INT8:
56504
+ return new Int8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength);
56505
+ case draco.DT_INT16:
56506
+ return new Int16Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength / 2);
56507
+ case draco.DT_INT32:
56508
+ return new Int32Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength / 4);
56509
+ case draco.DT_UINT8:
56510
+ return new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength);
56511
+ case draco.DT_UINT16:
56512
+ return new Uint16Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength / 2);
56513
+ case draco.DT_UINT32:
56514
+ return new Uint32Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength / 4);
56515
+ case draco.DT_FLOAT32:
56516
+ return new Float32Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength / 4);
56517
+ }
56518
+ return null;
56519
+ };
56520
+ const componentSizeInBytes = (dataType)=>{
56521
+ switch(dataType){
56522
+ case draco.DT_INT8:
56523
+ return 1;
56524
+ case draco.DT_INT16:
56525
+ return 2;
56526
+ case draco.DT_INT32:
56527
+ return 4;
56528
+ case draco.DT_UINT8:
56529
+ return 1;
56530
+ case draco.DT_UINT16:
56531
+ return 2;
56532
+ case draco.DT_UINT32:
56533
+ return 4;
56534
+ case draco.DT_FLOAT32:
56535
+ return 4;
56536
+ }
56537
+ return 1;
56538
+ };
56539
+ const toEngineDataType = (dataType)=>{
56540
+ switch(dataType){
56541
+ case draco.DT_INT8:
56542
+ return 0;
56543
+ case draco.DT_UINT8:
56544
+ return 1;
56545
+ case draco.DT_INT16:
56546
+ return 2;
56547
+ case draco.DT_UINT16:
56548
+ return 3;
56549
+ case draco.DT_INT32:
56550
+ return 4;
56551
+ case draco.DT_UINT32:
56552
+ return 5;
56553
+ case draco.DT_FLOAT32:
56554
+ return 6;
56555
+ default:
56556
+ return 6;
56557
+ }
56558
+ };
56559
+ const attributeSizeInBytes = (attribute)=>{
56560
+ return attribute.num_components() * componentSizeInBytes(attribute.data_type());
56561
+ };
56562
+ const attributeOrder = {
56563
+ 0: 0,
56564
+ 1: 1,
56565
+ 5: 2,
56566
+ 2: 3,
56567
+ 7: 4,
56568
+ 8: 5,
56569
+ 4: 6,
56570
+ 3: 7
56571
+ };
56572
+ const generateNormals = (vertices, indices)=>{
56573
+ const subtract = (dst, a, b)=>{
56574
+ dst[0] = a[0] - b[0];
56575
+ dst[1] = a[1] - b[1];
56576
+ dst[2] = a[2] - b[2];
56577
+ };
56578
+ const cross = (dst, a, b)=>{
56579
+ dst[0] = a[1] * b[2] - b[1] * a[2];
56580
+ dst[1] = a[2] * b[0] - b[2] * a[0];
56581
+ dst[2] = a[0] * b[1] - b[0] * a[1];
56582
+ };
56583
+ const normalize = (dst, offset)=>{
56584
+ const a = dst[offset + 0];
56585
+ const b = dst[offset + 1];
56586
+ const c = dst[offset + 2];
56587
+ const l = 1.0 / Math.sqrt(a * a + b * b + c * c);
56588
+ dst[offset + 0] *= l;
56589
+ dst[offset + 1] *= l;
56590
+ dst[offset + 2] *= l;
56591
+ };
56592
+ const copy = (dst, src, srcOffset)=>{
56593
+ for(let i = 0; i < 3; ++i){
56594
+ dst[i] = src[srcOffset + i];
56595
+ }
56596
+ };
56597
+ const numTriangles = indices.length / 3;
56598
+ const numVertices = vertices.length / 3;
56599
+ const result = new Float32Array(vertices.length);
56600
+ const a = [
56601
+ 0,
56602
+ 0,
56603
+ 0
56604
+ ], b = [
56605
+ 0,
56606
+ 0,
56607
+ 0
56608
+ ], c = [
56609
+ 0,
56610
+ 0,
56611
+ 0
56612
+ ], t1 = [
56613
+ 0,
56614
+ 0,
56615
+ 0
56616
+ ], t2 = [
56617
+ 0,
56618
+ 0,
56619
+ 0
56620
+ ], n = [
56621
+ 0,
56622
+ 0,
56623
+ 0
56624
+ ];
56625
+ for(let i = 0; i < numTriangles; ++i){
56626
+ const v0 = indices[i * 3 + 0] * 3;
56627
+ const v1 = indices[i * 3 + 1] * 3;
56628
+ const v2 = indices[i * 3 + 2] * 3;
56629
+ copy(a, vertices, v0);
56630
+ copy(b, vertices, v1);
56631
+ copy(c, vertices, v2);
56632
+ subtract(t1, b, a);
56633
+ subtract(t2, c, a);
56634
+ cross(n, t1, t2);
56635
+ normalize(n, 0);
56636
+ for(let j = 0; j < 3; ++j){
56637
+ result[v0 + j] += n[j];
56638
+ result[v1 + j] += n[j];
56639
+ result[v2 + j] += n[j];
56640
+ }
56641
+ }
56642
+ for(let i = 0; i < numVertices; ++i){
56643
+ normalize(result, i * 3);
56644
+ }
56645
+ return new Uint8Array(result.buffer);
56646
+ };
56647
+ const decodeMesh = (inputBuffer)=>{
56648
+ const result = {};
56649
+ const buffer = new draco.DecoderBuffer();
56650
+ buffer.Init(inputBuffer, inputBuffer.length);
56651
+ const decoder = new draco.Decoder();
56652
+ if (decoder.GetEncodedGeometryType(buffer) !== draco.TRIANGULAR_MESH) {
56653
+ result.error = 'Failed to decode draco mesh: not a mesh';
56654
+ return result;
56655
+ }
56656
+ const mesh = new draco.Mesh();
56657
+ const status = decoder.DecodeBufferToMesh(buffer, mesh);
56658
+ if (!status || !status.ok() || draco.getPointer(mesh) === 0) {
56659
+ result.error = 'Failed to decode draco asset';
56660
+ return result;
56661
+ }
56662
+ const numIndices = mesh.num_faces() * 3;
56663
+ const shortIndices = mesh.num_points() <= 65535;
56664
+ const indicesSize = numIndices * (shortIndices ? 2 : 4);
56665
+ const indicesPtr = draco._malloc(indicesSize);
56666
+ if (shortIndices) {
56667
+ decoder.GetTrianglesUInt16Array(mesh, indicesSize, indicesPtr);
56668
+ result.indices = new Uint16Array(draco.HEAPU16.buffer, indicesPtr, numIndices).slice().buffer;
56669
+ } else {
56670
+ decoder.GetTrianglesUInt32Array(mesh, indicesSize, indicesPtr);
56671
+ result.indices = new Uint32Array(draco.HEAPU32.buffer, indicesPtr, numIndices).slice().buffer;
56672
+ }
56673
+ draco._free(indicesPtr);
56674
+ const attributes = [];
56675
+ for(let i = 0; i < mesh.num_attributes(); ++i){
56676
+ attributes.push(decoder.GetAttribute(mesh, i));
56677
+ }
56678
+ attributes.sort((a, b)=>{
56679
+ return (attributeOrder[a.attribute_type()] ?? attributeOrder.length) - (attributeOrder[b.attribute_type()] ?? attributeOrder.length);
56680
+ });
56681
+ let totalVertexSize = 0;
56682
+ const offsets = attributes.map((a)=>{
56683
+ const offset = totalVertexSize;
56684
+ totalVertexSize += Math.ceil(attributeSizeInBytes(a) / 4) * 4;
56685
+ return offset;
56686
+ });
56687
+ const hasNormals = attributes.some((a)=>a.attribute_type() === NORMAL_ATTRIBUTE);
56688
+ let normalOffset = offsets[1] ?? 0;
56689
+ if (!hasNormals) {
56690
+ normalOffset = offsets[0] + Math.ceil(attributeSizeInBytes(attributes[0]) / 4) * 4;
56691
+ for(let i = 1; i < offsets.length; ++i){
56692
+ offsets[i] += 12;
56693
+ }
56694
+ totalVertexSize += 12;
56695
+ }
56696
+ result.attributes = attributes.map((a, i)=>({
56697
+ id: a.unique_id(),
56698
+ dataType: toEngineDataType(a.data_type()),
56699
+ numComponents: a.num_components(),
56700
+ offset: offsets[i]
56701
+ }));
56702
+ if (!hasNormals) {
56703
+ result.attributes.splice(1, 0, {
56704
+ id: -1,
56705
+ dataType: 6,
56706
+ numComponents: 3,
56707
+ offset: normalOffset
56708
+ });
56709
+ }
56710
+ result.stride = totalVertexSize;
56711
+ result.vertices = new ArrayBuffer(mesh.num_points() * totalVertexSize);
56712
+ const dst = new Uint8Array(result.vertices);
56713
+ for(let i = 0; i < mesh.num_attributes(); ++i){
56714
+ const attribute = attributes[i];
56715
+ const sizeInBytes = attributeSizeInBytes(attribute);
56716
+ const ptrSize = mesh.num_points() * sizeInBytes;
56717
+ const ptr = draco._malloc(ptrSize);
56718
+ decoder.GetAttributeDataArrayForAllPoints(mesh, attribute, attribute.data_type(), ptrSize, ptr);
56719
+ const src = new Uint8Array(draco.HEAPU8.buffer, ptr, ptrSize);
56720
+ for(let j = 0; j < mesh.num_points(); ++j){
56721
+ for(let c = 0; c < sizeInBytes; ++c){
56722
+ dst[j * totalVertexSize + offsets[i] + c] = src[j * sizeInBytes + c];
56723
+ }
56724
+ }
56725
+ if (!hasNormals && attribute.attribute_type() === POSITION_ATTRIBUTE) {
56726
+ const normals = generateNormals(wrap(src, attribute.data_type()), shortIndices ? new Uint16Array(result.indices) : new Uint32Array(result.indices));
56727
+ for(let j = 0; j < mesh.num_points(); ++j){
56728
+ for(let c = 0; c < 12; ++c){
56729
+ dst[j * totalVertexSize + normalOffset + c] = normals[j * 12 + c];
56730
+ }
56731
+ }
56732
+ }
56733
+ draco._free(ptr);
56734
+ }
56735
+ draco.destroy(mesh);
56736
+ draco.destroy(decoder);
56737
+ draco.destroy(buffer);
56738
+ return result;
56739
+ };
56740
+ const decode = (data)=>{
56741
+ const result = decodeMesh(new Uint8Array(data.buffer));
56742
+ self.postMessage({
56743
+ jobId: data.jobId,
56744
+ error: result.error,
56745
+ indices: result.indices,
56746
+ vertices: result.vertices,
56747
+ attributes: result.attributes,
56748
+ stride: result.stride
56749
+ }, [
56750
+ result.indices,
56751
+ result.vertices
56752
+ ].filter((t)=>t != null));
56753
+ };
56754
+ const workQueue = [];
56755
+ self.onmessage = (message)=>{
56756
+ const data = message.data;
56757
+ switch(data.type){
56758
+ case 'init':
56759
+ self.DracoDecoderModule({
56760
+ instantiateWasm: (imports, successCallback)=>{
56761
+ WebAssembly.instantiate(data.module, imports).then((result)=>successCallback(result)).catch((reason)=>console.error(`instantiate failed + ${reason}`));
56762
+ return {};
56763
+ }
56764
+ }).then((instance)=>{
56765
+ draco = instance;
56766
+ workQueue.forEach((data)=>decode(data));
56767
+ });
56768
+ break;
56769
+ case 'decodeMesh':
56770
+ if (draco) {
56771
+ decode(data);
56772
+ } else {
56773
+ workQueue.push(data);
56774
+ }
56775
+ break;
56776
+ }
56777
+ };
56778
+ }
56779
+
56780
+ const downloadMaxRetries = 3;
56781
+ class JobQueue {
56782
+ init(workers) {
56783
+ workers.forEach((worker)=>{
56784
+ worker.addEventListener('message', (message)=>{
56785
+ const data = message.data;
56786
+ const callback = this.jobCallbacks.get(data.jobId);
56787
+ if (callback) {
56788
+ callback(data.error, {
56789
+ indices: data.indices,
56790
+ vertices: data.vertices,
56791
+ attributes: data.attributes,
56792
+ stride: data.stride
56793
+ });
56794
+ }
56795
+ this.jobCallbacks.delete(data.jobId);
56796
+ if (this.jobQueue.length > 0) {
56797
+ const job = this.jobQueue.shift();
56798
+ this.run(worker, job);
56799
+ } else {
56800
+ const index2 = this.workers[2].indexOf(worker);
56801
+ if (index2 !== -1) {
56802
+ this.workers[2].splice(index2, 1);
56803
+ this.workers[1].push(worker);
56804
+ } else {
56805
+ const index1 = this.workers[1].indexOf(worker);
56806
+ if (index1 !== -1) {
56807
+ this.workers[1].splice(index1, 1);
56808
+ this.workers[0].push(worker);
56809
+ }
56810
+ }
56811
+ }
56812
+ });
56813
+ });
56814
+ this.workers[0] = workers;
56815
+ while(this.jobQueue.length && (this.workers[0].length || this.workers[1].length)){
56816
+ const job = this.jobQueue.shift();
56817
+ if (this.workers[0].length > 0) {
56818
+ const worker = this.workers[0].shift();
56819
+ this.workers[1].push(worker);
56820
+ this.run(worker, job);
56821
+ } else {
56822
+ const worker = this.workers[1].shift();
56823
+ this.workers[2].push(worker);
56824
+ this.run(worker, job);
56825
+ }
56826
+ }
56827
+ }
56828
+ enqueueJob(buffer, callback) {
56829
+ const job = {
56830
+ jobId: this.jobId++,
56831
+ buffer: buffer
56832
+ };
56833
+ this.jobCallbacks.set(job.jobId, callback);
56834
+ if (this.workers[0].length > 0) {
56835
+ const worker = this.workers[0].shift();
56836
+ this.workers[1].push(worker);
56837
+ this.run(worker, job);
56838
+ } else if (this.workers[1].length > 0) {
56839
+ const worker = this.workers[1].shift();
56840
+ this.workers[2].push(worker);
56841
+ this.run(worker, job);
56842
+ } else {
56843
+ this.jobQueue.push(job);
56844
+ }
56845
+ }
56846
+ constructor(){
56847
+ this.workers = [
56848
+ [],
56849
+ [],
56850
+ []
56851
+ ];
56852
+ this.jobId = 0;
56853
+ this.jobQueue = [];
56854
+ this.jobCallbacks = new Map();
56855
+ this.run = (worker, job)=>{
56856
+ worker.postMessage({
56857
+ type: 'decodeMesh',
56858
+ jobId: job.jobId,
56859
+ buffer: job.buffer
56860
+ }, [
56861
+ job.buffer
56862
+ ]);
56863
+ };
56864
+ }
56865
+ }
56866
+ const downloadScript = (url)=>{
56867
+ return new Promise((resolve, reject)=>{
56868
+ const options = {
56869
+ cache: true,
56870
+ responseType: 'text',
56871
+ retry: downloadMaxRetries > 0,
56872
+ maxRetries: downloadMaxRetries
56873
+ };
56874
+ http.get(url, options, (err, response)=>{
56875
+ if (err) {
56876
+ reject(err);
56877
+ } else {
56878
+ resolve(response);
56879
+ }
56880
+ });
56881
+ });
56882
+ };
56883
+ const compileModule = (url)=>{
56884
+ const compileManual = ()=>{
56885
+ return fetch(url).then((result)=>result.arrayBuffer()).then((buffer)=>WebAssembly.compile(buffer));
56886
+ };
56887
+ const compileStreaming = ()=>{
56888
+ return WebAssembly.compileStreaming(fetch(url)).catch((err)=>{
56889
+ return compileManual();
56890
+ });
56891
+ };
56892
+ return WebAssembly.compileStreaming ? compileStreaming() : compileManual();
56893
+ };
56894
+ const defaultNumWorkers$1 = 1;
56895
+ let jobQueue;
56896
+ const initializeWorkers = (config)=>{
56897
+ if (jobQueue) {
56898
+ return true;
56899
+ }
56900
+ if (!config) {
56901
+ {
56902
+ const moduleConfig = WasmModule.getConfig('DracoDecoderModule');
56903
+ if (moduleConfig) {
56904
+ config = {
56905
+ jsUrl: moduleConfig.glueUrl,
56906
+ wasmUrl: moduleConfig.wasmUrl,
56907
+ numWorkers: moduleConfig.numWorkers
56908
+ };
56909
+ } else {
56910
+ config = {
56911
+ jsUrl: 'draco.wasm.js',
56912
+ wasmUrl: 'draco.wasm.wasm',
56913
+ numWorkers: defaultNumWorkers$1
56914
+ };
56915
+ }
56916
+ }
56917
+ }
56918
+ if (!config.jsUrl || !config.wasmUrl) {
56919
+ return false;
56920
+ }
56921
+ jobQueue = new JobQueue();
56922
+ Promise.all([
56923
+ downloadScript(config.jsUrl),
56924
+ compileModule(config.wasmUrl)
56925
+ ]).then(([dracoSource, dracoModule])=>{
56926
+ const code = [
56927
+ '/* draco */',
56928
+ dracoSource,
56929
+ '/* worker */',
56930
+ `(\n${DracoWorker.toString()}\n)()\n\n`
56931
+ ].join('\n');
56932
+ const blob = new Blob([
56933
+ code
56934
+ ], {
56935
+ type: "application/javascript"
56936
+ });
56937
+ const workerUrl = URL.createObjectURL(blob);
56938
+ const numWorkers = Math.max(1, Math.min(16, config.numWorkers || defaultNumWorkers$1));
56939
+ const workers = [];
56940
+ for(let i = 0; i < numWorkers; ++i){
56941
+ const worker = new Worker(workerUrl);
56942
+ worker.postMessage({
56943
+ type: 'init',
56944
+ module: dracoModule
56945
+ });
56946
+ workers.push(worker);
56947
+ }
56948
+ jobQueue.init(workers);
56949
+ });
56950
+ return true;
56951
+ };
56952
+ const dracoDecode = (buffer, callback)=>{
56953
+ if (!initializeWorkers()) {
56954
+ return false;
56955
+ }
56956
+ jobQueue.enqueueJob(buffer, callback);
56957
+ return true;
56958
+ };
56959
+
56960
+ class GlbResources {
56961
+ destroy() {
56962
+ if (this.renders) {
56963
+ this.renders.forEach((render)=>{
56964
+ render.meshes = null;
56965
+ });
56966
+ }
56967
+ }
56968
+ }
56969
+ const isDataURI = (uri)=>{
56970
+ return /^data:[^\n\r,\u2028\u2029]*,.*$/i.test(uri);
56971
+ };
56972
+ const getDataURIMimeType = (uri)=>{
56973
+ return uri.substring(uri.indexOf(':') + 1, uri.indexOf(';'));
56974
+ };
56975
+ const getNumComponents = (accessorType)=>{
56976
+ switch(accessorType){
56977
+ case 'SCALAR':
56978
+ return 1;
56979
+ case 'VEC2':
56980
+ return 2;
56981
+ case 'VEC3':
56982
+ return 3;
56983
+ case 'VEC4':
56984
+ return 4;
56985
+ case 'MAT2':
56986
+ return 4;
56987
+ case 'MAT3':
56988
+ return 9;
56989
+ case 'MAT4':
56990
+ return 16;
56991
+ default:
56992
+ return 3;
56993
+ }
56994
+ };
56995
+ const getComponentType = (componentType)=>{
56996
+ switch(componentType){
56997
+ case 5120:
56998
+ return TYPE_INT8;
56999
+ case 5121:
57000
+ return TYPE_UINT8;
57001
+ case 5122:
57002
+ return TYPE_INT16;
57003
+ case 5123:
57004
+ return TYPE_UINT16;
57005
+ case 5124:
57006
+ return TYPE_INT32;
57007
+ case 5125:
57008
+ return TYPE_UINT32;
57009
+ case 5126:
57010
+ return TYPE_FLOAT32;
57011
+ default:
57012
+ return 0;
57013
+ }
57014
+ };
57015
+ const getComponentSizeInBytes = (componentType)=>{
57016
+ switch(componentType){
57017
+ case 5120:
57018
+ return 1;
57019
+ case 5121:
57020
+ return 1;
57021
+ case 5122:
57022
+ return 2;
57023
+ case 5123:
57024
+ return 2;
57025
+ case 5124:
57026
+ return 4;
57027
+ case 5125:
57028
+ return 4;
57029
+ case 5126:
57030
+ return 4;
57031
+ default:
57032
+ return 0;
57033
+ }
57034
+ };
57035
+ const getComponentDataType = (componentType)=>{
57036
+ switch(componentType){
57037
+ case 5120:
57038
+ return Int8Array;
57039
+ case 5121:
57040
+ return Uint8Array;
57041
+ case 5122:
57042
+ return Int16Array;
57043
+ case 5123:
57044
+ return Uint16Array;
57045
+ case 5124:
57046
+ return Int32Array;
57047
+ case 5125:
57048
+ return Uint32Array;
57049
+ case 5126:
57050
+ return Float32Array;
57051
+ default:
57052
+ return null;
57053
+ }
57054
+ };
57055
+ const gltfToEngineSemanticMap = {
57056
+ 'POSITION': SEMANTIC_POSITION,
57057
+ 'NORMAL': SEMANTIC_NORMAL,
57058
+ 'TANGENT': SEMANTIC_TANGENT,
57059
+ 'COLOR_0': SEMANTIC_COLOR,
57060
+ 'JOINTS_0': SEMANTIC_BLENDINDICES,
57061
+ 'WEIGHTS_0': SEMANTIC_BLENDWEIGHT,
57062
+ 'TEXCOORD_0': SEMANTIC_TEXCOORD0,
57063
+ 'TEXCOORD_1': SEMANTIC_TEXCOORD1,
57064
+ 'TEXCOORD_2': SEMANTIC_TEXCOORD2,
57065
+ 'TEXCOORD_3': SEMANTIC_TEXCOORD3,
57066
+ 'TEXCOORD_4': SEMANTIC_TEXCOORD4,
57067
+ 'TEXCOORD_5': SEMANTIC_TEXCOORD5,
57068
+ 'TEXCOORD_6': SEMANTIC_TEXCOORD6,
57069
+ 'TEXCOORD_7': SEMANTIC_TEXCOORD7
57070
+ };
57071
+ const attributeOrder = {
57072
+ [SEMANTIC_POSITION]: 0,
57073
+ [SEMANTIC_NORMAL]: 1,
57074
+ [SEMANTIC_TANGENT]: 2,
57075
+ [SEMANTIC_COLOR]: 3,
57076
+ [SEMANTIC_BLENDINDICES]: 4,
57077
+ [SEMANTIC_BLENDWEIGHT]: 5,
57078
+ [SEMANTIC_TEXCOORD0]: 6,
57079
+ [SEMANTIC_TEXCOORD1]: 7,
57080
+ [SEMANTIC_TEXCOORD2]: 8,
57081
+ [SEMANTIC_TEXCOORD3]: 9,
57082
+ [SEMANTIC_TEXCOORD4]: 10,
57083
+ [SEMANTIC_TEXCOORD5]: 11,
57084
+ [SEMANTIC_TEXCOORD6]: 12,
57085
+ [SEMANTIC_TEXCOORD7]: 13
57086
+ };
57087
+ const getDequantizeFunc = (srcType)=>{
57088
+ switch(srcType){
57089
+ case TYPE_INT8:
57090
+ return (x)=>Math.max(x / 127.0, -1);
57091
+ case TYPE_UINT8:
57092
+ return (x)=>x / 255.0;
57093
+ case TYPE_INT16:
57094
+ return (x)=>Math.max(x / 32767.0, -1);
57095
+ case TYPE_UINT16:
57096
+ return (x)=>x / 65535.0;
57097
+ default:
57098
+ return (x)=>x;
57099
+ }
57100
+ };
57101
+ const dequantizeArray = (dstArray, srcArray, srcType)=>{
57102
+ const convFunc = getDequantizeFunc(srcType);
57103
+ const len = srcArray.length;
57104
+ for(let i = 0; i < len; ++i){
57105
+ dstArray[i] = convFunc(srcArray[i]);
57106
+ }
57107
+ return dstArray;
57108
+ };
57109
+ const getAccessorData = (gltfAccessor, bufferViews, flatten = false)=>{
57110
+ const numComponents = getNumComponents(gltfAccessor.type);
57111
+ const dataType = getComponentDataType(gltfAccessor.componentType);
57112
+ if (!dataType) {
57113
+ return null;
57114
+ }
57115
+ let result;
57116
+ if (gltfAccessor.sparse) {
57117
+ const sparse = gltfAccessor.sparse;
57118
+ const indicesAccessor = {
57119
+ count: sparse.count,
57120
+ type: 'SCALAR'
57121
+ };
57122
+ const indices = getAccessorData(Object.assign(indicesAccessor, sparse.indices), bufferViews, true);
57123
+ const valuesAccessor = {
57124
+ count: sparse.count,
57125
+ type: gltfAccessor.type,
57126
+ componentType: gltfAccessor.componentType
57127
+ };
57128
+ const values = getAccessorData(Object.assign(valuesAccessor, sparse.values), bufferViews, true);
57129
+ if (gltfAccessor.hasOwnProperty('bufferView')) {
57130
+ const baseAccessor = {
57131
+ bufferView: gltfAccessor.bufferView,
57132
+ byteOffset: gltfAccessor.byteOffset,
57133
+ componentType: gltfAccessor.componentType,
57134
+ count: gltfAccessor.count,
57135
+ type: gltfAccessor.type
57136
+ };
57137
+ result = getAccessorData(baseAccessor, bufferViews, true).slice();
57138
+ } else {
57139
+ result = new dataType(gltfAccessor.count * numComponents);
57140
+ }
57141
+ for(let i = 0; i < sparse.count; ++i){
57142
+ const targetIndex = indices[i];
57143
+ for(let j = 0; j < numComponents; ++j){
57144
+ result[targetIndex * numComponents + j] = values[i * numComponents + j];
57145
+ }
57146
+ }
57147
+ } else {
57148
+ if (gltfAccessor.hasOwnProperty('bufferView')) {
57149
+ const bufferView = bufferViews[gltfAccessor.bufferView];
57150
+ if (flatten && bufferView.hasOwnProperty('byteStride')) {
57151
+ const bytesPerElement = numComponents * dataType.BYTES_PER_ELEMENT;
57152
+ const storage = new ArrayBuffer(gltfAccessor.count * bytesPerElement);
57153
+ const tmpArray = new Uint8Array(storage);
57154
+ let dstOffset = 0;
57155
+ for(let i = 0; i < gltfAccessor.count; ++i){
57156
+ let srcOffset = (gltfAccessor.byteOffset || 0) + i * bufferView.byteStride;
57157
+ for(let b = 0; b < bytesPerElement; ++b){
57158
+ tmpArray[dstOffset++] = bufferView[srcOffset++];
57159
+ }
57160
+ }
57161
+ result = new dataType(storage);
57162
+ } else {
57163
+ result = new dataType(bufferView.buffer, bufferView.byteOffset + (gltfAccessor.byteOffset || 0), gltfAccessor.count * numComponents);
57164
+ }
57165
+ } else {
57166
+ result = new dataType(gltfAccessor.count * numComponents);
57167
+ }
57168
+ }
57169
+ return result;
57170
+ };
57171
+ const getAccessorDataFloat32 = (gltfAccessor, bufferViews)=>{
57172
+ const data = getAccessorData(gltfAccessor, bufferViews, true);
57173
+ if (data instanceof Float32Array || !gltfAccessor.normalized) {
57174
+ return data;
57175
+ }
57176
+ const float32Data = new Float32Array(data.length);
57177
+ dequantizeArray(float32Data, data, getComponentType(gltfAccessor.componentType));
57178
+ return float32Data;
57179
+ };
57180
+ const getAccessorBoundingBox = (gltfAccessor)=>{
57181
+ let min = gltfAccessor.min;
57182
+ let max = gltfAccessor.max;
57183
+ if (!min || !max) {
57184
+ return null;
57185
+ }
57186
+ if (gltfAccessor.normalized) {
57187
+ const ctype = getComponentType(gltfAccessor.componentType);
57188
+ min = dequantizeArray([], min, ctype);
57189
+ max = dequantizeArray([], max, ctype);
57190
+ }
57191
+ return new BoundingBox(new Vec3((max[0] + min[0]) * 0.5, (max[1] + min[1]) * 0.5, (max[2] + min[2]) * 0.5), new Vec3((max[0] - min[0]) * 0.5, (max[1] - min[1]) * 0.5, (max[2] - min[2]) * 0.5));
57192
+ };
57193
+ const getPrimitiveType = (primitive)=>{
57194
+ if (!primitive.hasOwnProperty('mode')) {
57195
+ return PRIMITIVE_TRIANGLES;
57196
+ }
57197
+ switch(primitive.mode){
57198
+ case 0:
57199
+ return PRIMITIVE_POINTS;
57200
+ case 1:
57201
+ return PRIMITIVE_LINES;
57202
+ case 2:
57203
+ return PRIMITIVE_LINELOOP;
57204
+ case 3:
57205
+ return PRIMITIVE_LINESTRIP;
57206
+ case 4:
57207
+ return PRIMITIVE_TRIANGLES;
57208
+ case 5:
57209
+ return PRIMITIVE_TRISTRIP;
57210
+ case 6:
57211
+ return PRIMITIVE_TRIFAN;
57212
+ default:
57213
+ return PRIMITIVE_TRIANGLES;
57214
+ }
57215
+ };
57216
+ const generateIndices = (numVertices)=>{
57217
+ const dummyIndices = new Uint16Array(numVertices);
57218
+ for(let i = 0; i < numVertices; i++){
57219
+ dummyIndices[i] = i;
57220
+ }
57221
+ return dummyIndices;
57222
+ };
57223
+ const generateNormals = (sourceDesc, indices)=>{
57224
+ const p = sourceDesc[SEMANTIC_POSITION];
57225
+ if (!p || p.components !== 3) {
57226
+ return;
57227
+ }
57228
+ let positions;
57229
+ if (p.size !== p.stride) {
57230
+ const srcStride = p.stride / typedArrayTypesByteSize[p.type];
57231
+ const src = new typedArrayTypes[p.type](p.buffer, p.offset, p.count * srcStride);
57232
+ positions = new typedArrayTypes[p.type](p.count * 3);
57233
+ for(let i = 0; i < p.count; ++i){
57234
+ positions[i * 3 + 0] = src[i * srcStride + 0];
57235
+ positions[i * 3 + 1] = src[i * srcStride + 1];
57236
+ positions[i * 3 + 2] = src[i * srcStride + 2];
57237
+ }
57238
+ } else {
57239
+ positions = new typedArrayTypes[p.type](p.buffer, p.offset, p.count * 3);
57240
+ }
57241
+ const numVertices = p.count;
57242
+ if (!indices) {
57243
+ indices = generateIndices(numVertices);
57244
+ }
57245
+ const normalsTemp = calculateNormals(positions, indices);
57246
+ const normals = new Float32Array(normalsTemp.length);
57247
+ normals.set(normalsTemp);
57248
+ sourceDesc[SEMANTIC_NORMAL] = {
57249
+ buffer: normals.buffer,
57250
+ size: 12,
57251
+ offset: 0,
57252
+ stride: 12,
57253
+ count: numVertices,
57254
+ components: 3,
57255
+ type: TYPE_FLOAT32
57256
+ };
57257
+ };
57258
+ const cloneTexture = (texture)=>{
57259
+ const shallowCopyLevels = (texture)=>{
57260
+ const result = [];
57261
+ for(let mip = 0; mip < texture._levels.length; ++mip){
57262
+ let level = [];
57263
+ if (texture.cubemap) {
57264
+ for(let face = 0; face < 6; ++face){
57265
+ level.push(texture._levels[mip][face]);
57266
+ }
57267
+ } else {
57268
+ level = texture._levels[mip];
57269
+ }
57270
+ result.push(level);
57271
+ }
57272
+ return result;
57273
+ };
57274
+ const result = new Texture(texture.device, texture);
57275
+ result._levels = shallowCopyLevels(texture);
57276
+ return result;
57277
+ };
57278
+ const cloneTextureAsset = (src)=>{
57279
+ const result = new Asset(`${src.name}_clone`, src.type, src.file, src.data, src.options);
57280
+ result.loaded = true;
57281
+ result.resource = cloneTexture(src.resource);
57282
+ src.registry.add(result);
57283
+ return result;
57284
+ };
57285
+ const createVertexBufferInternal = (device, sourceDesc)=>{
57286
+ const positionDesc = sourceDesc[SEMANTIC_POSITION];
57287
+ if (!positionDesc) {
57288
+ return null;
57289
+ }
57290
+ const numVertices = positionDesc.count;
57291
+ const vertexDesc = [];
57292
+ for(const semantic in sourceDesc){
57293
+ if (sourceDesc.hasOwnProperty(semantic)) {
57294
+ const element = {
57295
+ semantic: semantic,
57296
+ components: sourceDesc[semantic].components,
57297
+ type: sourceDesc[semantic].type,
57298
+ normalize: !!sourceDesc[semantic].normalize
57299
+ };
57300
+ if (!VertexFormat.isElementValid(device, element)) {
57301
+ element.components++;
57302
+ }
57303
+ vertexDesc.push(element);
57304
+ }
57305
+ }
57306
+ vertexDesc.sort((lhs, rhs)=>{
57307
+ return attributeOrder[lhs.semantic] - attributeOrder[rhs.semantic];
57308
+ });
57309
+ let i, j, k;
57310
+ let source, target, sourceOffset;
57311
+ const vertexFormat = new VertexFormat(device, vertexDesc);
57312
+ let isCorrectlyInterleaved = true;
57313
+ for(i = 0; i < vertexFormat.elements.length; ++i){
57314
+ target = vertexFormat.elements[i];
57315
+ source = sourceDesc[target.name];
57316
+ sourceOffset = source.offset - positionDesc.offset;
57317
+ if (source.buffer !== positionDesc.buffer || source.stride !== target.stride || source.size !== target.size || sourceOffset !== target.offset) {
57318
+ isCorrectlyInterleaved = false;
57319
+ break;
57320
+ }
57321
+ }
57322
+ const vertexBuffer = new VertexBuffer(device, vertexFormat, numVertices);
57323
+ const vertexData = vertexBuffer.lock();
57324
+ const targetArray = new Uint32Array(vertexData);
57325
+ let sourceArray;
57326
+ if (isCorrectlyInterleaved) {
57327
+ sourceArray = new Uint32Array(positionDesc.buffer, positionDesc.offset, numVertices * vertexBuffer.format.size / 4);
57328
+ targetArray.set(sourceArray);
57329
+ } else {
57330
+ let targetStride, sourceStride;
57331
+ for(i = 0; i < vertexBuffer.format.elements.length; ++i){
57332
+ target = vertexBuffer.format.elements[i];
57333
+ targetStride = target.stride / 4;
57334
+ source = sourceDesc[target.name];
57335
+ sourceStride = source.stride / 4;
57336
+ sourceArray = new Uint32Array(source.buffer, source.offset, (source.count - 1) * sourceStride + (source.size + 3) / 4);
57337
+ let src = 0;
57338
+ let dst = target.offset / 4;
57339
+ const kend = Math.floor((source.size + 3) / 4);
57340
+ for(j = 0; j < numVertices; ++j){
57341
+ for(k = 0; k < kend; ++k){
57342
+ targetArray[dst + k] = sourceArray[src + k];
57343
+ }
57344
+ src += sourceStride;
57345
+ dst += targetStride;
57346
+ }
57347
+ }
57348
+ }
57349
+ vertexBuffer.unlock();
57350
+ return vertexBuffer;
57351
+ };
57352
+ const createVertexBuffer = (device, attributes, indices, accessors, bufferViews, vertexBufferDict)=>{
57353
+ const useAttributes = {};
57354
+ const attribIds = [];
57355
+ for(const attrib in attributes){
57356
+ if (attributes.hasOwnProperty(attrib) && gltfToEngineSemanticMap.hasOwnProperty(attrib)) {
57357
+ useAttributes[attrib] = attributes[attrib];
57358
+ attribIds.push(`${attrib}:${attributes[attrib]}`);
57359
+ }
57360
+ }
57361
+ attribIds.sort();
57362
+ const vbKey = attribIds.join();
57363
+ let vb = vertexBufferDict[vbKey];
57364
+ if (!vb) {
57365
+ const sourceDesc = {};
57366
+ for(const attrib in useAttributes){
57367
+ const accessor = accessors[attributes[attrib]];
57368
+ const accessorData = getAccessorData(accessor, bufferViews);
57369
+ const bufferView = bufferViews[accessor.bufferView];
57370
+ const semantic = gltfToEngineSemanticMap[attrib];
57371
+ const size = getNumComponents(accessor.type) * getComponentSizeInBytes(accessor.componentType);
57372
+ const stride = bufferView && bufferView.hasOwnProperty('byteStride') ? bufferView.byteStride : size;
57373
+ sourceDesc[semantic] = {
57374
+ buffer: accessorData.buffer,
57375
+ size: size,
57376
+ offset: accessorData.byteOffset,
57377
+ stride: stride,
57378
+ count: accessor.count,
57379
+ components: getNumComponents(accessor.type),
57380
+ type: getComponentType(accessor.componentType),
57381
+ normalize: accessor.normalized
57382
+ };
57383
+ }
57384
+ if (!sourceDesc.hasOwnProperty(SEMANTIC_NORMAL)) {
57385
+ generateNormals(sourceDesc, indices);
57386
+ }
57387
+ vb = createVertexBufferInternal(device, sourceDesc);
57388
+ vertexBufferDict[vbKey] = vb;
57389
+ }
57390
+ return vb;
57391
+ };
57392
+ const createSkin = (device, gltfSkin, accessors, bufferViews, nodes, glbSkins)=>{
57393
+ let i, j, bindMatrix;
57394
+ const joints = gltfSkin.joints;
57395
+ const numJoints = joints.length;
57396
+ const ibp = [];
57397
+ if (gltfSkin.hasOwnProperty('inverseBindMatrices')) {
57398
+ const inverseBindMatrices = gltfSkin.inverseBindMatrices;
57399
+ const ibmData = getAccessorData(accessors[inverseBindMatrices], bufferViews, true);
57400
+ const ibmValues = [];
57401
+ for(i = 0; i < numJoints; i++){
57402
+ for(j = 0; j < 16; j++){
57403
+ ibmValues[j] = ibmData[i * 16 + j];
57404
+ }
57405
+ bindMatrix = new Mat4();
57406
+ bindMatrix.set(ibmValues);
57407
+ ibp.push(bindMatrix);
57408
+ }
57409
+ } else {
57410
+ for(i = 0; i < numJoints; i++){
57411
+ bindMatrix = new Mat4();
57412
+ ibp.push(bindMatrix);
57413
+ }
57414
+ }
57415
+ const boneNames = [];
57416
+ for(i = 0; i < numJoints; i++){
57417
+ boneNames[i] = nodes[joints[i]].name;
57418
+ }
57419
+ const key = boneNames.join('#');
57420
+ let skin = glbSkins.get(key);
57421
+ if (!skin) {
57422
+ skin = new Skin(device, ibp, boneNames);
57423
+ glbSkins.set(key, skin);
57424
+ }
57425
+ return skin;
57426
+ };
57427
+ const createDracoMesh = (device, primitive, accessors, bufferViews, meshVariants, meshDefaultMaterials, promises)=>{
57428
+ const result = new Mesh(device);
57429
+ result.aabb = getAccessorBoundingBox(accessors[primitive.attributes.POSITION]);
57430
+ promises.push(new Promise((resolve, reject)=>{
57431
+ const dracoExt = primitive.extensions.KHR_draco_mesh_compression;
57432
+ dracoDecode(bufferViews[dracoExt.bufferView].slice().buffer, (err, decompressedData)=>{
57433
+ if (err) {
57434
+ console.log(err);
57435
+ reject(err);
57436
+ } else {
57437
+ const idToSemantic = {};
57438
+ for (const [name, id] of Object.entries(dracoExt.attributes)){
57439
+ idToSemantic[id] = gltfToEngineSemanticMap[name];
57440
+ }
57441
+ idToSemantic[-1] = SEMANTIC_NORMAL;
57442
+ const vertexDesc = [];
57443
+ for (const attr of decompressedData.attributes){
57444
+ const semantic = idToSemantic[attr.id];
57445
+ if (semantic !== undefined) {
57446
+ let normalize = false;
57447
+ if (attr.id !== -1) {
57448
+ for (const [name, id] of Object.entries(dracoExt.attributes)){
57449
+ if (id === attr.id && primitive.attributes[name] !== undefined) {
57450
+ const accessor = accessors[primitive.attributes[name]];
57451
+ normalize = accessor.normalized ?? (semantic === SEMANTIC_COLOR && (attr.dataType === TYPE_UINT8 || attr.dataType === TYPE_UINT16));
57452
+ break;
57453
+ }
57454
+ }
57455
+ }
57456
+ vertexDesc.push({
57457
+ semantic: semantic,
57458
+ components: attr.numComponents,
57459
+ type: attr.dataType,
57460
+ normalize: normalize,
57461
+ offset: attr.offset,
57462
+ stride: decompressedData.stride
57463
+ });
57464
+ }
57465
+ }
57466
+ const vertexFormat = new VertexFormat(device, vertexDesc);
57467
+ const numVertices = decompressedData.vertices.byteLength / decompressedData.stride;
57468
+ const indexFormat = numVertices <= 65535 ? INDEXFORMAT_UINT16 : INDEXFORMAT_UINT32;
57469
+ const numIndices = decompressedData.indices.byteLength / (numVertices <= 65535 ? 2 : 4);
57470
+ const vertexBuffer = new VertexBuffer(device, vertexFormat, numVertices, {
57471
+ data: decompressedData.vertices
57472
+ });
57473
+ const indexBuffer = new IndexBuffer(device, indexFormat, numIndices, BUFFER_STATIC, decompressedData.indices);
57474
+ result.vertexBuffer = vertexBuffer;
57475
+ result.indexBuffer[0] = indexBuffer;
57476
+ result.primitive[0].type = getPrimitiveType(primitive);
57477
+ result.primitive[0].base = 0;
57478
+ result.primitive[0].count = indexBuffer ? numIndices : numVertices;
57479
+ result.primitive[0].indexed = !!indexBuffer;
57480
+ resolve();
57481
+ }
57482
+ });
57483
+ }));
57484
+ if (primitive?.extensions?.KHR_materials_variants) {
57485
+ const variants = primitive.extensions.KHR_materials_variants;
57486
+ const tempMapping = {};
57487
+ variants.mappings.forEach((mapping)=>{
57488
+ mapping.variants.forEach((variant)=>{
57489
+ tempMapping[variant] = mapping.material;
57490
+ });
57491
+ });
57492
+ meshVariants[result.id] = tempMapping;
57493
+ }
57494
+ meshDefaultMaterials[result.id] = primitive.material;
57495
+ return result;
57496
+ };
57497
+ const createMesh = (device, gltfMesh, accessors, bufferViews, vertexBufferDict, meshVariants, meshDefaultMaterials, assetOptions, promises)=>{
57498
+ const meshes = [];
57499
+ gltfMesh.primitives.forEach((primitive)=>{
57500
+ if (primitive.extensions?.KHR_draco_mesh_compression) {
57501
+ meshes.push(createDracoMesh(device, primitive, accessors, bufferViews, meshVariants, meshDefaultMaterials, promises));
57502
+ } else {
57503
+ let indices = primitive.hasOwnProperty('indices') ? getAccessorData(accessors[primitive.indices], bufferViews, true) : null;
57504
+ const vertexBuffer = createVertexBuffer(device, primitive.attributes, indices, accessors, bufferViews, vertexBufferDict);
57505
+ const primitiveType = getPrimitiveType(primitive);
57506
+ const mesh = new Mesh(device);
57507
+ mesh.vertexBuffer = vertexBuffer;
57508
+ mesh.primitive[0].type = primitiveType;
57509
+ mesh.primitive[0].base = 0;
57510
+ mesh.primitive[0].indexed = indices !== null;
57511
+ if (indices !== null) {
57512
+ let indexFormat;
57513
+ if (indices instanceof Uint8Array) {
57514
+ indexFormat = INDEXFORMAT_UINT8;
57515
+ } else if (indices instanceof Uint16Array) {
57516
+ indexFormat = INDEXFORMAT_UINT16;
57517
+ } else {
57518
+ indexFormat = INDEXFORMAT_UINT32;
57519
+ }
57520
+ if (indexFormat === INDEXFORMAT_UINT8 && device.isWebGPU) {
57521
+ indexFormat = INDEXFORMAT_UINT16;
57522
+ indices = new Uint16Array(indices);
57523
+ }
57524
+ const indexBuffer = new IndexBuffer(device, indexFormat, indices.length, BUFFER_STATIC, indices);
57525
+ mesh.indexBuffer[0] = indexBuffer;
57526
+ mesh.primitive[0].count = indices.length;
57527
+ } else {
57528
+ mesh.primitive[0].count = vertexBuffer.numVertices;
57529
+ }
57530
+ if (primitive.hasOwnProperty('extensions') && primitive.extensions.hasOwnProperty('KHR_materials_variants')) {
57531
+ const variants = primitive.extensions.KHR_materials_variants;
57532
+ const tempMapping = {};
57533
+ variants.mappings.forEach((mapping)=>{
57534
+ mapping.variants.forEach((variant)=>{
57535
+ tempMapping[variant] = mapping.material;
57536
+ });
57537
+ });
57538
+ meshVariants[mesh.id] = tempMapping;
57539
+ }
57540
+ meshDefaultMaterials[mesh.id] = primitive.material;
57541
+ let accessor = accessors[primitive.attributes.POSITION];
57542
+ mesh.aabb = getAccessorBoundingBox(accessor);
57543
+ if (primitive.hasOwnProperty('targets')) {
57544
+ const targets = [];
57545
+ primitive.targets.forEach((target, index)=>{
57546
+ const options = {};
57547
+ if (target.hasOwnProperty('POSITION')) {
57548
+ accessor = accessors[target.POSITION];
57549
+ options.deltaPositions = getAccessorDataFloat32(accessor, bufferViews);
57550
+ options.aabb = getAccessorBoundingBox(accessor);
57551
+ }
57552
+ if (target.hasOwnProperty('NORMAL')) {
57553
+ accessor = accessors[target.NORMAL];
57554
+ options.deltaNormals = getAccessorDataFloat32(accessor, bufferViews);
57555
+ }
57556
+ if (gltfMesh.hasOwnProperty('extras') && gltfMesh.extras.hasOwnProperty('targetNames')) {
57557
+ options.name = gltfMesh.extras.targetNames[index];
57558
+ } else {
57559
+ options.name = index.toString(10);
57560
+ }
57561
+ if (gltfMesh.hasOwnProperty('weights')) {
57562
+ options.defaultWeight = gltfMesh.weights[index];
57563
+ }
57564
+ options.preserveData = assetOptions.morphPreserveData;
57565
+ targets.push(new MorphTarget(options));
57566
+ });
57567
+ mesh.morph = new Morph(targets, device, {
57568
+ preferHighPrecision: assetOptions.morphPreferHighPrecision
57569
+ });
57570
+ }
57571
+ meshes.push(mesh);
57572
+ }
57573
+ });
57574
+ return meshes;
57575
+ };
57576
+ const extractTextureTransform = (source, material, maps)=>{
57577
+ let map;
57578
+ const texCoord = source.texCoord;
57579
+ if (texCoord) {
57580
+ for(map = 0; map < maps.length; ++map){
57581
+ material[`${maps[map]}MapUv`] = texCoord;
57582
+ }
57583
+ }
57584
+ const zeros = [
57585
+ 0,
57586
+ 0
57587
+ ];
57588
+ const ones = [
57589
+ 1,
57590
+ 1
57591
+ ];
57592
+ const textureTransform = source.extensions?.KHR_texture_transform;
57593
+ if (textureTransform) {
57594
+ const offset = textureTransform.offset || zeros;
57595
+ const scale = textureTransform.scale || ones;
57596
+ const rotation = textureTransform.rotation ? -textureTransform.rotation * math.RAD_TO_DEG : 0;
57597
+ const tilingVec = new Vec2(scale[0], scale[1]);
57598
+ const offsetVec = new Vec2(offset[0], 1.0 - scale[1] - offset[1]);
57599
+ for(map = 0; map < maps.length; ++map){
57600
+ material[`${maps[map]}MapTiling`] = tilingVec;
57601
+ material[`${maps[map]}MapOffset`] = offsetVec;
57602
+ material[`${maps[map]}MapRotation`] = rotation;
57603
+ }
57604
+ }
57605
+ };
57606
+ const extensionPbrSpecGlossiness = (data, material, textures)=>{
57607
+ let texture;
57608
+ if (data.hasOwnProperty('diffuseFactor')) {
57609
+ const [r, g, b, a] = data.diffuseFactor;
57610
+ material.diffuse.set(r, g, b).gamma();
57611
+ material.opacity = a;
57612
+ } else {
57613
+ material.diffuse.set(1, 1, 1);
57614
+ material.opacity = 1;
57615
+ }
57616
+ if (data.hasOwnProperty('diffuseTexture')) {
57617
+ const diffuseTexture = data.diffuseTexture;
57618
+ texture = textures[diffuseTexture.index];
57619
+ material.diffuseMap = texture;
57620
+ material.diffuseMapChannel = 'rgb';
57621
+ material.opacityMap = texture;
57622
+ material.opacityMapChannel = 'a';
57623
+ extractTextureTransform(diffuseTexture, material, [
57624
+ 'diffuse',
57625
+ 'opacity'
57626
+ ]);
57627
+ }
57628
+ material.useMetalness = false;
57629
+ if (data.hasOwnProperty('specularFactor')) {
57630
+ const [r, g, b] = data.specularFactor;
57631
+ material.specular.set(r, g, b).gamma();
57632
+ } else {
57633
+ material.specular.set(1, 1, 1);
57634
+ }
57635
+ if (data.hasOwnProperty('glossinessFactor')) {
57636
+ material.gloss = data.glossinessFactor;
57637
+ } else {
57638
+ material.gloss = 1.0;
57639
+ }
57640
+ if (data.hasOwnProperty('specularGlossinessTexture')) {
57641
+ const specularGlossinessTexture = data.specularGlossinessTexture;
57642
+ material.specularMap = material.glossMap = textures[specularGlossinessTexture.index];
57643
+ material.specularMapChannel = 'rgb';
57644
+ material.glossMapChannel = 'a';
57645
+ extractTextureTransform(specularGlossinessTexture, material, [
57646
+ 'gloss',
57647
+ 'metalness'
57648
+ ]);
57649
+ }
57650
+ };
57651
+ const extensionClearCoat = (data, material, textures)=>{
57652
+ if (data.hasOwnProperty('clearcoatFactor')) {
57653
+ material.clearCoat = data.clearcoatFactor * 0.25;
57654
+ } else {
57655
+ material.clearCoat = 0;
57656
+ }
57657
+ if (data.hasOwnProperty('clearcoatTexture')) {
57658
+ const clearcoatTexture = data.clearcoatTexture;
57659
+ material.clearCoatMap = textures[clearcoatTexture.index];
57660
+ material.clearCoatMapChannel = 'r';
57661
+ extractTextureTransform(clearcoatTexture, material, [
57662
+ 'clearCoat'
57663
+ ]);
57664
+ }
57665
+ if (data.hasOwnProperty('clearcoatRoughnessFactor')) {
57666
+ material.clearCoatGloss = data.clearcoatRoughnessFactor;
57667
+ } else {
57668
+ material.clearCoatGloss = 0;
57669
+ }
57670
+ if (data.hasOwnProperty('clearcoatRoughnessTexture')) {
57671
+ const clearcoatRoughnessTexture = data.clearcoatRoughnessTexture;
57672
+ material.clearCoatGlossMap = textures[clearcoatRoughnessTexture.index];
57673
+ material.clearCoatGlossMapChannel = 'g';
57674
+ extractTextureTransform(clearcoatRoughnessTexture, material, [
57675
+ 'clearCoatGloss'
57676
+ ]);
57677
+ }
57678
+ if (data.hasOwnProperty('clearcoatNormalTexture')) {
57679
+ const clearcoatNormalTexture = data.clearcoatNormalTexture;
57680
+ material.clearCoatNormalMap = textures[clearcoatNormalTexture.index];
57681
+ extractTextureTransform(clearcoatNormalTexture, material, [
57682
+ 'clearCoatNormal'
57683
+ ]);
57684
+ if (clearcoatNormalTexture.hasOwnProperty('scale')) {
57685
+ material.clearCoatBumpiness = clearcoatNormalTexture.scale;
57686
+ } else {
57687
+ material.clearCoatBumpiness = 1;
57688
+ }
57689
+ }
57690
+ material.clearCoatGlossInvert = true;
57691
+ };
57692
+ const extensionUnlit = (data, material, textures)=>{
57693
+ material.useLighting = false;
57694
+ material.emissive.copy(material.diffuse);
57695
+ material.emissiveMap = material.diffuseMap;
57696
+ material.emissiveMapUv = material.diffuseMapUv;
57697
+ material.emissiveMapTiling.copy(material.diffuseMapTiling);
57698
+ material.emissiveMapOffset.copy(material.diffuseMapOffset);
57699
+ material.emissiveMapRotation = material.diffuseMapRotation;
57700
+ material.emissiveMapChannel = material.diffuseMapChannel;
57701
+ material.emissiveVertexColor = material.diffuseVertexColor;
57702
+ material.emissiveVertexColorChannel = material.diffuseVertexColorChannel;
57703
+ material.useLighting = false;
57704
+ material.useSkybox = false;
57705
+ material.diffuse.set(1, 1, 1);
57706
+ material.diffuseMap = null;
57707
+ material.diffuseVertexColor = false;
57708
+ };
57709
+ const extensionSpecular = (data, material, textures)=>{
57710
+ material.useMetalnessSpecularColor = true;
57711
+ if (data.hasOwnProperty('specularColorTexture')) {
57712
+ material.specularMap = textures[data.specularColorTexture.index];
57713
+ material.specularMapChannel = 'rgb';
57714
+ extractTextureTransform(data.specularColorTexture, material, [
57715
+ 'specular'
57716
+ ]);
57717
+ }
57718
+ if (data.hasOwnProperty('specularColorFactor')) {
57719
+ const [r, g, b] = data.specularColorFactor;
57720
+ material.specular.set(r, g, b).gamma();
57721
+ } else {
57722
+ material.specular.set(1, 1, 1);
57723
+ }
57724
+ if (data.hasOwnProperty('specularFactor')) {
57725
+ material.specularityFactor = data.specularFactor;
57726
+ } else {
57727
+ material.specularityFactor = 1;
57728
+ }
57729
+ if (data.hasOwnProperty('specularTexture')) {
57730
+ material.specularityFactorMapChannel = 'a';
57731
+ material.specularityFactorMap = textures[data.specularTexture.index];
57732
+ extractTextureTransform(data.specularTexture, material, [
57733
+ 'specularityFactor'
57734
+ ]);
57735
+ }
57736
+ };
57737
+ const extensionIor = (data, material, textures)=>{
57738
+ if (data.hasOwnProperty('ior')) {
57739
+ material.refractionIndex = 1.0 / data.ior;
57740
+ }
57741
+ };
57742
+ const extensionDispersion = (data, material, textures)=>{
57743
+ if (data.hasOwnProperty('dispersion')) {
57744
+ material.dispersion = data.dispersion;
57745
+ }
57746
+ };
57747
+ const extensionTransmission = (data, material, textures)=>{
57748
+ material.blendType = BLEND_NORMAL;
57749
+ material.useDynamicRefraction = true;
57750
+ if (data.hasOwnProperty('transmissionFactor')) {
57751
+ material.refraction = data.transmissionFactor;
57752
+ }
57753
+ if (data.hasOwnProperty('transmissionTexture')) {
57754
+ material.refractionMapChannel = 'r';
57755
+ material.refractionMap = textures[data.transmissionTexture.index];
57756
+ extractTextureTransform(data.transmissionTexture, material, [
57757
+ 'refraction'
57758
+ ]);
57759
+ }
57760
+ };
57761
+ const extensionSheen = (data, material, textures)=>{
57762
+ material.useSheen = true;
57763
+ if (data.hasOwnProperty('sheenColorFactor')) {
57764
+ const [r, g, b] = data.sheenColorFactor;
57765
+ material.sheen.set(r, g, b).gamma();
57766
+ } else {
57767
+ material.sheen.set(1, 1, 1);
57768
+ }
57769
+ if (data.hasOwnProperty('sheenColorTexture')) {
57770
+ material.sheenMap = textures[data.sheenColorTexture.index];
57771
+ extractTextureTransform(data.sheenColorTexture, material, [
57772
+ 'sheen'
57773
+ ]);
57774
+ }
57775
+ material.sheenGloss = data.hasOwnProperty('sheenRoughnessFactor') ? data.sheenRoughnessFactor : 0.0;
57776
+ if (data.hasOwnProperty('sheenRoughnessTexture')) {
57777
+ material.sheenGlossMap = textures[data.sheenRoughnessTexture.index];
57778
+ material.sheenGlossMapChannel = 'a';
57779
+ extractTextureTransform(data.sheenRoughnessTexture, material, [
57780
+ 'sheenGloss'
57781
+ ]);
57782
+ }
57783
+ material.sheenGlossInvert = true;
57784
+ };
57785
+ const extensionVolume = (data, material, textures)=>{
57786
+ material.blendType = BLEND_NORMAL;
57787
+ material.useDynamicRefraction = true;
57788
+ if (data.hasOwnProperty('thicknessFactor')) {
57789
+ material.thickness = data.thicknessFactor;
57790
+ }
57791
+ if (data.hasOwnProperty('thicknessTexture')) {
57792
+ material.thicknessMap = textures[data.thicknessTexture.index];
57793
+ material.thicknessMapChannel = 'g';
57794
+ extractTextureTransform(data.thicknessTexture, material, [
57795
+ 'thickness'
57796
+ ]);
57797
+ }
57798
+ if (data.hasOwnProperty('attenuationDistance')) {
57799
+ material.attenuationDistance = data.attenuationDistance;
57800
+ }
57801
+ if (data.hasOwnProperty('attenuationColor')) {
57802
+ const [r, g, b] = data.attenuationColor;
57803
+ material.attenuation.set(r, g, b).gamma();
57804
+ }
57805
+ };
57806
+ const extensionEmissiveStrength = (data, material, textures)=>{
57807
+ if (data.hasOwnProperty('emissiveStrength')) {
57808
+ material.emissiveIntensity = data.emissiveStrength;
57809
+ }
57810
+ };
57811
+ const extensionIridescence = (data, material, textures)=>{
57812
+ material.useIridescence = true;
57813
+ if (data.hasOwnProperty('iridescenceFactor')) {
57814
+ material.iridescence = data.iridescenceFactor;
57815
+ }
57816
+ if (data.hasOwnProperty('iridescenceTexture')) {
57817
+ material.iridescenceMapChannel = 'r';
57818
+ material.iridescenceMap = textures[data.iridescenceTexture.index];
57819
+ extractTextureTransform(data.iridescenceTexture, material, [
57820
+ 'iridescence'
57821
+ ]);
57822
+ }
57823
+ if (data.hasOwnProperty('iridescenceIor')) {
57824
+ material.iridescenceRefractionIndex = data.iridescenceIor;
57825
+ }
57826
+ if (data.hasOwnProperty('iridescenceThicknessMinimum')) {
57827
+ material.iridescenceThicknessMin = data.iridescenceThicknessMinimum;
57828
+ }
57829
+ if (data.hasOwnProperty('iridescenceThicknessMaximum')) {
57830
+ material.iridescenceThicknessMax = data.iridescenceThicknessMaximum;
57831
+ }
57832
+ if (data.hasOwnProperty('iridescenceThicknessTexture')) {
57833
+ material.iridescenceThicknessMapChannel = 'g';
57834
+ material.iridescenceThicknessMap = textures[data.iridescenceThicknessTexture.index];
57835
+ extractTextureTransform(data.iridescenceThicknessTexture, material, [
57836
+ 'iridescenceThickness'
57837
+ ]);
57838
+ }
57839
+ };
57840
+ const extensionAnisotropy = (data, material, textures)=>{
57841
+ material.enableGGXSpecular = true;
57842
+ if (data.hasOwnProperty('anisotropyStrength')) {
57843
+ material.anisotropyIntensity = data.anisotropyStrength;
57844
+ } else {
57845
+ material.anisotropyIntensity = 0;
57846
+ }
57847
+ if (data.hasOwnProperty('anisotropyTexture')) {
57848
+ const anisotropyTexture = data.anisotropyTexture;
57849
+ material.anisotropyMap = textures[anisotropyTexture.index];
57850
+ extractTextureTransform(anisotropyTexture, material, [
57851
+ 'anisotropy'
57852
+ ]);
57853
+ }
57854
+ if (data.hasOwnProperty('anisotropyRotation')) {
57855
+ material.anisotropyRotation = data.anisotropyRotation * math.RAD_TO_DEG;
57856
+ } else {
57857
+ material.anisotropyRotation = 0;
57858
+ }
57859
+ };
57860
+ const createMaterial = (gltfMaterial, textures)=>{
57861
+ const material = new StandardMaterial();
57862
+ if (gltfMaterial.hasOwnProperty('name')) {
57863
+ material.name = gltfMaterial.name;
57864
+ }
57865
+ material.occludeSpecular = SPECOCC_AO;
57866
+ material.diffuseVertexColor = true;
57867
+ material.specularTint = true;
57868
+ material.specularVertexColor = true;
57869
+ material.specular.set(1, 1, 1);
57870
+ material.gloss = 1;
57871
+ material.glossInvert = true;
57872
+ material.useMetalness = true;
57873
+ let texture;
57874
+ if (gltfMaterial.hasOwnProperty('pbrMetallicRoughness')) {
57875
+ const pbrData = gltfMaterial.pbrMetallicRoughness;
57876
+ if (pbrData.hasOwnProperty('baseColorFactor')) {
57877
+ const [r, g, b, a] = pbrData.baseColorFactor;
57878
+ material.diffuse.set(r, g, b).gamma();
57879
+ material.opacity = a;
57880
+ }
57881
+ if (pbrData.hasOwnProperty('baseColorTexture')) {
57882
+ const baseColorTexture = pbrData.baseColorTexture;
57883
+ texture = textures[baseColorTexture.index];
57884
+ material.diffuseMap = texture;
57885
+ material.diffuseMapChannel = 'rgb';
57886
+ material.opacityMap = texture;
57887
+ material.opacityMapChannel = 'a';
57888
+ extractTextureTransform(baseColorTexture, material, [
57889
+ 'diffuse',
57890
+ 'opacity'
57891
+ ]);
57892
+ }
57893
+ if (pbrData.hasOwnProperty('metallicFactor')) {
57894
+ material.metalness = pbrData.metallicFactor;
57895
+ }
57896
+ if (pbrData.hasOwnProperty('roughnessFactor')) {
57897
+ material.gloss = pbrData.roughnessFactor;
57898
+ }
57899
+ if (pbrData.hasOwnProperty('metallicRoughnessTexture')) {
57900
+ const metallicRoughnessTexture = pbrData.metallicRoughnessTexture;
57901
+ material.metalnessMap = material.glossMap = textures[metallicRoughnessTexture.index];
57902
+ material.metalnessMapChannel = 'b';
57903
+ material.glossMapChannel = 'g';
57904
+ extractTextureTransform(metallicRoughnessTexture, material, [
57905
+ 'gloss',
57906
+ 'metalness'
57907
+ ]);
57908
+ }
57909
+ }
57910
+ if (gltfMaterial.hasOwnProperty('normalTexture')) {
57911
+ const normalTexture = gltfMaterial.normalTexture;
57912
+ material.normalMap = textures[normalTexture.index];
57913
+ extractTextureTransform(normalTexture, material, [
57914
+ 'normal'
57915
+ ]);
57916
+ if (normalTexture.hasOwnProperty('scale')) {
57917
+ material.bumpiness = normalTexture.scale;
57918
+ }
57919
+ }
57920
+ if (gltfMaterial.hasOwnProperty('occlusionTexture')) {
57921
+ const occlusionTexture = gltfMaterial.occlusionTexture;
57922
+ material.aoMap = textures[occlusionTexture.index];
57923
+ material.aoMapChannel = 'r';
57924
+ extractTextureTransform(occlusionTexture, material, [
57925
+ 'ao'
57926
+ ]);
57927
+ }
57928
+ if (gltfMaterial.hasOwnProperty('emissiveFactor')) {
57929
+ const [r, g, b] = gltfMaterial.emissiveFactor;
57930
+ material.emissive.set(r, g, b).gamma();
57931
+ }
57932
+ if (gltfMaterial.hasOwnProperty('emissiveTexture')) {
57933
+ const emissiveTexture = gltfMaterial.emissiveTexture;
57934
+ material.emissiveMap = textures[emissiveTexture.index];
57935
+ extractTextureTransform(emissiveTexture, material, [
57936
+ 'emissive'
57937
+ ]);
57938
+ }
57939
+ if (gltfMaterial.hasOwnProperty('alphaMode')) {
57940
+ switch(gltfMaterial.alphaMode){
57941
+ case 'MASK':
57942
+ material.blendType = BLEND_NONE;
57943
+ if (gltfMaterial.hasOwnProperty('alphaCutoff')) {
57944
+ material.alphaTest = gltfMaterial.alphaCutoff;
57945
+ } else {
57946
+ material.alphaTest = 0.5;
57947
+ }
57948
+ break;
57949
+ case 'BLEND':
57950
+ material.blendType = BLEND_NORMAL;
57951
+ material.depthWrite = false;
57952
+ break;
57953
+ default:
57954
+ case 'OPAQUE':
57955
+ material.blendType = BLEND_NONE;
57956
+ break;
57957
+ }
57958
+ } else {
57959
+ material.blendType = BLEND_NONE;
57960
+ }
57961
+ if (gltfMaterial.hasOwnProperty('doubleSided')) {
57962
+ material.twoSidedLighting = gltfMaterial.doubleSided;
57963
+ material.cull = gltfMaterial.doubleSided ? CULLFACE_NONE : CULLFACE_BACK;
57964
+ } else {
57965
+ material.twoSidedLighting = false;
57966
+ material.cull = CULLFACE_BACK;
57967
+ }
57968
+ const extensions = {
57969
+ 'KHR_materials_clearcoat': extensionClearCoat,
57970
+ 'KHR_materials_emissive_strength': extensionEmissiveStrength,
57971
+ 'KHR_materials_ior': extensionIor,
57972
+ 'KHR_materials_dispersion': extensionDispersion,
57973
+ 'KHR_materials_iridescence': extensionIridescence,
57974
+ 'KHR_materials_pbrSpecularGlossiness': extensionPbrSpecGlossiness,
57975
+ 'KHR_materials_sheen': extensionSheen,
57976
+ 'KHR_materials_specular': extensionSpecular,
57977
+ 'KHR_materials_transmission': extensionTransmission,
57978
+ 'KHR_materials_unlit': extensionUnlit,
57979
+ 'KHR_materials_volume': extensionVolume,
57980
+ 'KHR_materials_anisotropy': extensionAnisotropy
57981
+ };
57982
+ if (gltfMaterial.hasOwnProperty('extensions')) {
57983
+ for(const key in gltfMaterial.extensions){
57984
+ const extensionFunc = extensions[key];
57985
+ if (extensionFunc !== undefined) {
57986
+ extensionFunc(gltfMaterial.extensions[key], material, textures);
57987
+ }
57988
+ }
57989
+ }
57990
+ material.update();
57991
+ return material;
57992
+ };
57993
+ const createAnimation = (gltfAnimation, animationIndex, gltfAccessors, bufferViews, nodes, meshes, gltfNodes)=>{
57994
+ const createAnimData = (gltfAccessor)=>{
57995
+ return new AnimData(getNumComponents(gltfAccessor.type), getAccessorDataFloat32(gltfAccessor, bufferViews));
57996
+ };
57997
+ const interpMap = {
57998
+ 'STEP': INTERPOLATION_STEP,
57999
+ 'LINEAR': INTERPOLATION_LINEAR,
58000
+ 'CUBICSPLINE': INTERPOLATION_CUBIC
58001
+ };
58002
+ const inputMap = {};
58003
+ const outputMap = {};
58004
+ const curveMap = {};
58005
+ let outputCounter = 1;
58006
+ let i;
58007
+ for(i = 0; i < gltfAnimation.samplers.length; ++i){
58008
+ const sampler = gltfAnimation.samplers[i];
58009
+ if (!inputMap.hasOwnProperty(sampler.input)) {
58010
+ inputMap[sampler.input] = createAnimData(gltfAccessors[sampler.input]);
58011
+ }
58012
+ if (!outputMap.hasOwnProperty(sampler.output)) {
58013
+ outputMap[sampler.output] = createAnimData(gltfAccessors[sampler.output]);
58014
+ }
58015
+ const interpolation = sampler.hasOwnProperty('interpolation') && interpMap.hasOwnProperty(sampler.interpolation) ? interpMap[sampler.interpolation] : INTERPOLATION_LINEAR;
58016
+ const curve = {
58017
+ paths: [],
58018
+ input: sampler.input,
58019
+ output: sampler.output,
58020
+ interpolation: interpolation
58021
+ };
58022
+ curveMap[i] = curve;
58023
+ }
58024
+ const quatArrays = [];
58025
+ const transformSchema = {
58026
+ 'translation': 'localPosition',
58027
+ 'rotation': 'localRotation',
58028
+ 'scale': 'localScale'
58029
+ };
58030
+ const constructNodePath = (node)=>{
58031
+ const path = [];
58032
+ while(node){
58033
+ path.unshift(node.name);
58034
+ node = node.parent;
58035
+ }
58036
+ return path;
58037
+ };
58038
+ const createMorphTargetCurves = (curve, gltfNode, entityPath)=>{
58039
+ const out = outputMap[curve.output];
58040
+ if (!out) {
58041
+ return;
58042
+ }
58043
+ let targetNames;
58044
+ if (meshes && meshes[gltfNode.mesh]) {
58045
+ const mesh = meshes[gltfNode.mesh];
58046
+ if (mesh.hasOwnProperty('extras') && mesh.extras.hasOwnProperty('targetNames')) {
58047
+ targetNames = mesh.extras.targetNames;
58048
+ }
58049
+ }
58050
+ const outData = out.data;
58051
+ const morphTargetCount = outData.length / inputMap[curve.input].data.length;
58052
+ const keyframeCount = outData.length / morphTargetCount;
58053
+ const singleBufferSize = keyframeCount * 4;
58054
+ const buffer = new ArrayBuffer(singleBufferSize * morphTargetCount);
58055
+ for(let j = 0; j < morphTargetCount; j++){
58056
+ const morphTargetOutput = new Float32Array(buffer, singleBufferSize * j, keyframeCount);
58057
+ for(let k = 0; k < keyframeCount; k++){
58058
+ morphTargetOutput[k] = outData[k * morphTargetCount + j];
58059
+ }
58060
+ const output = new AnimData(1, morphTargetOutput);
58061
+ const weightName = targetNames?.[j] ? `name.${targetNames[j]}` : j;
58062
+ outputMap[-outputCounter] = output;
58063
+ const morphCurve = {
58064
+ paths: [
58065
+ {
58066
+ entityPath: entityPath,
58067
+ component: 'graph',
58068
+ propertyPath: [
58069
+ `weight.${weightName}`
58070
+ ]
58071
+ }
58072
+ ],
58073
+ input: curve.input,
58074
+ output: -outputCounter,
58075
+ interpolation: curve.interpolation
58076
+ };
58077
+ outputCounter++;
58078
+ curveMap[`morphCurve-${i}-${j}`] = morphCurve;
58079
+ }
58080
+ };
58081
+ for(i = 0; i < gltfAnimation.channels.length; ++i){
58082
+ const channel = gltfAnimation.channels[i];
58083
+ const target = channel.target;
58084
+ const curve = curveMap[channel.sampler];
58085
+ const node = nodes[target.node];
58086
+ const gltfNode = gltfNodes[target.node];
58087
+ const entityPath = constructNodePath(node);
58088
+ if (target.path.startsWith('weights')) {
58089
+ createMorphTargetCurves(curve, gltfNode, entityPath);
58090
+ curveMap[channel.sampler].morphCurve = true;
58091
+ } else {
58092
+ curve.paths.push({
58093
+ entityPath: entityPath,
58094
+ component: 'graph',
58095
+ propertyPath: [
58096
+ transformSchema[target.path]
58097
+ ]
58098
+ });
58099
+ }
58100
+ }
58101
+ const inputs = [];
58102
+ const outputs = [];
58103
+ const curves = [];
58104
+ for(const inputKey in inputMap){
58105
+ inputs.push(inputMap[inputKey]);
58106
+ inputMap[inputKey] = inputs.length - 1;
58107
+ }
58108
+ for(const outputKey in outputMap){
58109
+ outputs.push(outputMap[outputKey]);
58110
+ outputMap[outputKey] = outputs.length - 1;
58111
+ }
58112
+ for(const curveKey in curveMap){
58113
+ const curveData = curveMap[curveKey];
58114
+ if (curveData.morphCurve) {
58115
+ continue;
58116
+ }
58117
+ curves.push(new AnimCurve(curveData.paths, inputMap[curveData.input], outputMap[curveData.output], curveData.interpolation));
58118
+ if (curveData.paths.length > 0 && curveData.paths[0].propertyPath[0] === 'localRotation' && curveData.interpolation !== INTERPOLATION_CUBIC) {
58119
+ quatArrays.push(curves[curves.length - 1].output);
58120
+ }
58121
+ }
58122
+ quatArrays.sort();
58123
+ let prevIndex = null;
58124
+ let data;
58125
+ for(i = 0; i < quatArrays.length; ++i){
58126
+ const index = quatArrays[i];
58127
+ if (i === 0 || index !== prevIndex) {
58128
+ data = outputs[index];
58129
+ if (data.components === 4) {
58130
+ const d = data.data;
58131
+ const len = d.length - 4;
58132
+ for(let j = 0; j < len; j += 4){
58133
+ const dp = d[j + 0] * d[j + 4] + d[j + 1] * d[j + 5] + d[j + 2] * d[j + 6] + d[j + 3] * d[j + 7];
58134
+ if (dp < 0) {
58135
+ d[j + 4] *= -1;
58136
+ d[j + 5] *= -1;
58137
+ d[j + 6] *= -1;
58138
+ d[j + 7] *= -1;
58139
+ }
58140
+ }
58141
+ }
58142
+ prevIndex = index;
58143
+ }
58144
+ }
58145
+ let duration = 0;
58146
+ for(i = 0; i < inputs.length; i++){
58147
+ data = inputs[i]._data;
58148
+ duration = Math.max(duration, data.length === 0 ? 0 : data[data.length - 1]);
58149
+ }
58150
+ return new AnimTrack(gltfAnimation.hasOwnProperty('name') ? gltfAnimation.name : `animation_${animationIndex}`, duration, inputs, outputs, curves);
58151
+ };
58152
+ const tempMat = new Mat4();
58153
+ const tempVec = new Vec3();
58154
+ const tempQuat = new Quat();
58155
+ const createNode = (gltfNode, nodeIndex, nodeInstancingMap)=>{
58156
+ const entity = new GraphNode();
58157
+ if (gltfNode.hasOwnProperty('name') && gltfNode.name.length > 0) {
58158
+ entity.name = gltfNode.name;
58159
+ } else {
58160
+ entity.name = `node_${nodeIndex}`;
58161
+ }
58162
+ if (gltfNode.hasOwnProperty('matrix')) {
58163
+ tempMat.data.set(gltfNode.matrix);
58164
+ tempMat.getTranslation(tempVec);
58165
+ entity.setLocalPosition(tempVec);
58166
+ tempQuat.setFromMat4(tempMat);
58167
+ entity.setLocalRotation(tempQuat);
58168
+ tempMat.getScale(tempVec);
58169
+ tempVec.x *= tempMat.scaleSign;
58170
+ entity.setLocalScale(tempVec);
58171
+ }
58172
+ if (gltfNode.hasOwnProperty('rotation')) {
58173
+ const r = gltfNode.rotation;
58174
+ entity.setLocalRotation(r[0], r[1], r[2], r[3]);
58175
+ }
58176
+ if (gltfNode.hasOwnProperty('translation')) {
58177
+ const t = gltfNode.translation;
58178
+ entity.setLocalPosition(t[0], t[1], t[2]);
58179
+ }
58180
+ if (gltfNode.hasOwnProperty('scale')) {
58181
+ const s = gltfNode.scale;
58182
+ entity.setLocalScale(s[0], s[1], s[2]);
58183
+ }
58184
+ if (gltfNode.hasOwnProperty('extensions') && gltfNode.extensions.EXT_mesh_gpu_instancing) {
58185
+ nodeInstancingMap.set(gltfNode, {
58186
+ ext: gltfNode.extensions.EXT_mesh_gpu_instancing
58187
+ });
58188
+ }
58189
+ return entity;
58190
+ };
58191
+ const createCamera$1 = (gltfCamera, node)=>{
58192
+ const isOrthographic = gltfCamera.type === 'orthographic';
58193
+ const gltfProperties = isOrthographic ? gltfCamera.orthographic : gltfCamera.perspective;
58194
+ const componentData = {
58195
+ enabled: false,
58196
+ projection: isOrthographic ? PROJECTION_ORTHOGRAPHIC : PROJECTION_PERSPECTIVE,
58197
+ nearClip: gltfProperties.znear,
58198
+ aspectRatioMode: ASPECT_AUTO
58199
+ };
58200
+ if (gltfProperties.zfar) {
58201
+ componentData.farClip = gltfProperties.zfar;
58202
+ }
58203
+ if (isOrthographic) {
58204
+ componentData.orthoHeight = gltfProperties.ymag;
58205
+ if (gltfProperties.xmag && gltfProperties.ymag) {
58206
+ componentData.aspectRatioMode = ASPECT_MANUAL;
58207
+ componentData.aspectRatio = gltfProperties.xmag / gltfProperties.ymag;
58208
+ }
58209
+ } else {
58210
+ componentData.fov = gltfProperties.yfov * math.RAD_TO_DEG;
58211
+ if (gltfProperties.aspectRatio) {
58212
+ componentData.aspectRatioMode = ASPECT_MANUAL;
58213
+ componentData.aspectRatio = gltfProperties.aspectRatio;
58214
+ }
58215
+ }
58216
+ const cameraEntity = new Entity(gltfCamera.name);
58217
+ cameraEntity.addComponent('camera', componentData);
58218
+ return cameraEntity;
58219
+ };
58220
+ const createLight = (gltfLight, node)=>{
58221
+ const lightProps = {
58222
+ enabled: false,
58223
+ type: gltfLight.type === 'point' ? 'omni' : gltfLight.type,
58224
+ color: gltfLight.hasOwnProperty('color') ? new Color(gltfLight.color) : Color.WHITE,
58225
+ range: gltfLight.hasOwnProperty('range') ? gltfLight.range : 9999,
58226
+ falloffMode: LIGHTFALLOFF_INVERSESQUARED,
58227
+ intensity: gltfLight.hasOwnProperty('intensity') ? math.clamp(gltfLight.intensity, 0, 2) : 1
58228
+ };
58229
+ if (gltfLight.hasOwnProperty('spot')) {
58230
+ lightProps.innerConeAngle = gltfLight.spot.hasOwnProperty('innerConeAngle') ? gltfLight.spot.innerConeAngle * math.RAD_TO_DEG : 0;
58231
+ lightProps.outerConeAngle = gltfLight.spot.hasOwnProperty('outerConeAngle') ? gltfLight.spot.outerConeAngle * math.RAD_TO_DEG : 45;
58232
+ }
58233
+ if (gltfLight.hasOwnProperty('intensity')) {
58234
+ const outerAngleRad = gltfLight.spot?.outerConeAngle ?? Math.PI / 4;
58235
+ const innerAngleRad = gltfLight.spot?.innerConeAngle ?? 0;
58236
+ lightProps.luminance = gltfLight.intensity * Light.getLightUnitConversion(lightTypes[lightProps.type], outerAngleRad, innerAngleRad);
58237
+ }
58238
+ const lightEntity = new Entity(node.name);
58239
+ lightEntity.rotateLocal(90, 0, 0);
58240
+ lightEntity.addComponent('light', lightProps);
58241
+ return lightEntity;
58242
+ };
58243
+ const createSkins = (device, gltf, nodes, bufferViews)=>{
58244
+ if (!gltf.hasOwnProperty('skins') || gltf.skins.length === 0) {
58245
+ return [];
58246
+ }
58247
+ const glbSkins = new Map();
58248
+ return gltf.skins.map((gltfSkin)=>{
58249
+ return createSkin(device, gltfSkin, gltf.accessors, bufferViews, nodes, glbSkins);
58250
+ });
58251
+ };
58252
+ const createMeshes = (device, gltf, bufferViews, options)=>{
58253
+ const vertexBufferDict = {};
58254
+ const meshVariants = {};
58255
+ const meshDefaultMaterials = {};
58256
+ const promises = [];
58257
+ const valid = !options.skipMeshes && gltf?.meshes?.length && gltf?.accessors?.length && gltf?.bufferViews?.length;
58258
+ const meshes = valid ? gltf.meshes.map((gltfMesh)=>{
58259
+ return createMesh(device, gltfMesh, gltf.accessors, bufferViews, vertexBufferDict, meshVariants, meshDefaultMaterials, options, promises);
58260
+ }) : [];
58261
+ return {
58262
+ meshes,
58263
+ meshVariants,
58264
+ meshDefaultMaterials,
58265
+ promises
58266
+ };
58267
+ };
58268
+ const createMaterials = (gltf, textures, options)=>{
58269
+ if (!gltf.hasOwnProperty('materials') || gltf.materials.length === 0) {
58270
+ return [];
58271
+ }
58272
+ const preprocess = options?.material?.preprocess;
58273
+ const process = options?.material?.process ?? createMaterial;
58274
+ const postprocess = options?.material?.postprocess;
58275
+ return gltf.materials.map((gltfMaterial)=>{
58276
+ if (preprocess) {
58277
+ preprocess(gltfMaterial);
58278
+ }
58279
+ const material = process(gltfMaterial, textures);
58280
+ if (postprocess) {
58281
+ postprocess(gltfMaterial, material);
58282
+ }
58283
+ return material;
58284
+ });
58285
+ };
58286
+ const createVariants = (gltf)=>{
58287
+ if (!gltf.hasOwnProperty('extensions') || !gltf.extensions.hasOwnProperty('KHR_materials_variants')) {
58288
+ return null;
58289
+ }
58290
+ const data = gltf.extensions.KHR_materials_variants.variants;
58291
+ const variants = {};
58292
+ for(let i = 0; i < data.length; i++){
58293
+ variants[data[i].name] = i;
58294
+ }
58295
+ return variants;
58296
+ };
58297
+ const createAnimations = (gltf, nodes, bufferViews, options)=>{
58298
+ if (!gltf.hasOwnProperty('animations') || gltf.animations.length === 0) {
58299
+ return [];
58300
+ }
58301
+ const preprocess = options?.animation?.preprocess;
58302
+ const postprocess = options?.animation?.postprocess;
58303
+ return gltf.animations.map((gltfAnimation, index)=>{
58304
+ if (preprocess) {
58305
+ preprocess(gltfAnimation);
58306
+ }
58307
+ const animation = createAnimation(gltfAnimation, index, gltf.accessors, bufferViews, nodes, gltf.meshes, gltf.nodes);
58308
+ if (postprocess) {
58309
+ postprocess(gltfAnimation, animation);
58310
+ }
58311
+ return animation;
58312
+ });
58313
+ };
58314
+ const createInstancing = (device, gltf, nodeInstancingMap, bufferViews)=>{
58315
+ const accessors = gltf.accessors;
58316
+ nodeInstancingMap.forEach((data, entity)=>{
58317
+ const attributes = data.ext.attributes;
58318
+ let translations;
58319
+ if (attributes.hasOwnProperty('TRANSLATION')) {
58320
+ const accessor = accessors[attributes.TRANSLATION];
58321
+ translations = getAccessorDataFloat32(accessor, bufferViews);
58322
+ }
58323
+ let rotations;
58324
+ if (attributes.hasOwnProperty('ROTATION')) {
58325
+ const accessor = accessors[attributes.ROTATION];
58326
+ rotations = getAccessorDataFloat32(accessor, bufferViews);
58327
+ }
58328
+ let scales;
58329
+ if (attributes.hasOwnProperty('SCALE')) {
58330
+ const accessor = accessors[attributes.SCALE];
58331
+ scales = getAccessorDataFloat32(accessor, bufferViews);
58332
+ }
58333
+ const instanceCount = (translations ? translations.length / 3 : 0) || (rotations ? rotations.length / 4 : 0) || (scales ? scales.length / 3 : 0);
58334
+ if (instanceCount) {
58335
+ const matrices = new Float32Array(instanceCount * 16);
58336
+ const pos = new Vec3();
58337
+ const rot = new Quat();
58338
+ const scl = new Vec3(1, 1, 1);
58339
+ const matrix = new Mat4();
58340
+ let matrixIndex = 0;
58341
+ for(let i = 0; i < instanceCount; i++){
58342
+ const i3 = i * 3;
58343
+ if (translations) {
58344
+ pos.set(translations[i3], translations[i3 + 1], translations[i3 + 2]);
58345
+ }
58346
+ if (rotations) {
58347
+ const i4 = i * 4;
58348
+ rot.set(rotations[i4], rotations[i4 + 1], rotations[i4 + 2], rotations[i4 + 3]);
58349
+ }
58350
+ if (scales) {
58351
+ scl.set(scales[i3], scales[i3 + 1], scales[i3 + 2]);
58352
+ }
58353
+ matrix.setTRS(pos, rot, scl);
58354
+ for(let m = 0; m < 16; m++){
58355
+ matrices[matrixIndex++] = matrix.data[m];
58356
+ }
58357
+ }
58358
+ data.matrices = matrices;
58359
+ }
58360
+ });
58361
+ };
58362
+ const createNodes = (gltf, options, nodeInstancingMap)=>{
58363
+ if (!gltf.hasOwnProperty('nodes') || gltf.nodes.length === 0) {
58364
+ return [];
58365
+ }
58366
+ const preprocess = options?.node?.preprocess;
58367
+ const process = options?.node?.process ?? createNode;
58368
+ const postprocess = options?.node?.postprocess;
58369
+ const nodes = gltf.nodes.map((gltfNode, index)=>{
58370
+ if (preprocess) {
58371
+ preprocess(gltfNode);
58372
+ }
58373
+ const node = process(gltfNode, index, nodeInstancingMap);
58374
+ if (postprocess) {
58375
+ postprocess(gltfNode, node);
58376
+ }
58377
+ return node;
58378
+ });
58379
+ for(let i = 0; i < gltf.nodes.length; ++i){
58380
+ const gltfNode = gltf.nodes[i];
58381
+ if (gltfNode.hasOwnProperty('children')) {
58382
+ const parent = nodes[i];
58383
+ const uniqueNames = {};
58384
+ for(let j = 0; j < gltfNode.children.length; ++j){
58385
+ const child = nodes[gltfNode.children[j]];
58386
+ if (!child.parent) {
58387
+ if (uniqueNames.hasOwnProperty(child.name)) {
58388
+ child.name += uniqueNames[child.name]++;
58389
+ } else {
58390
+ uniqueNames[child.name] = 1;
58391
+ }
58392
+ parent.addChild(child);
58393
+ }
58394
+ }
58395
+ }
58396
+ }
58397
+ return nodes;
58398
+ };
58399
+ const createScenes = (gltf, nodes)=>{
58400
+ const scenes = [];
58401
+ const count = gltf.scenes.length;
58402
+ if (count === 1 && gltf.scenes[0].nodes?.length === 1) {
58403
+ const nodeIndex = gltf.scenes[0].nodes[0];
58404
+ scenes.push(nodes[nodeIndex]);
58405
+ } else {
58406
+ for(let i = 0; i < count; i++){
58407
+ const scene = gltf.scenes[i];
58408
+ if (scene.nodes) {
58409
+ const sceneRoot = new GraphNode(scene.name);
58410
+ for(let n = 0; n < scene.nodes.length; n++){
58411
+ const childNode = nodes[scene.nodes[n]];
58412
+ sceneRoot.addChild(childNode);
58413
+ }
58414
+ scenes.push(sceneRoot);
58415
+ }
58416
+ }
58417
+ }
58418
+ return scenes;
58419
+ };
58420
+ const createCameras = (gltf, nodes, options)=>{
58421
+ let cameras = null;
58422
+ if (gltf.hasOwnProperty('nodes') && gltf.hasOwnProperty('cameras') && gltf.cameras.length > 0) {
58423
+ const preprocess = options?.camera?.preprocess;
58424
+ const process = options?.camera?.process ?? createCamera$1;
58425
+ const postprocess = options?.camera?.postprocess;
58426
+ gltf.nodes.forEach((gltfNode, nodeIndex)=>{
58427
+ if (gltfNode.hasOwnProperty('camera')) {
58428
+ const gltfCamera = gltf.cameras[gltfNode.camera];
58429
+ if (gltfCamera) {
58430
+ if (preprocess) {
58431
+ preprocess(gltfCamera);
58432
+ }
58433
+ const camera = process(gltfCamera, nodes[nodeIndex]);
58434
+ if (postprocess) {
58435
+ postprocess(gltfCamera, camera);
58436
+ }
58437
+ if (camera) {
58438
+ if (!cameras) cameras = new Map();
58439
+ cameras.set(gltfNode, camera);
58440
+ }
58441
+ }
58442
+ }
58443
+ });
58444
+ }
58445
+ return cameras;
58446
+ };
58447
+ const createLights = (gltf, nodes, options)=>{
58448
+ let lights = null;
58449
+ if (gltf.hasOwnProperty('nodes') && gltf.hasOwnProperty('extensions') && gltf.extensions.hasOwnProperty('KHR_lights_punctual') && gltf.extensions.KHR_lights_punctual.hasOwnProperty('lights')) {
58450
+ const gltfLights = gltf.extensions.KHR_lights_punctual.lights;
58451
+ if (gltfLights.length) {
58452
+ const preprocess = options?.light?.preprocess;
58453
+ const process = options?.light?.process ?? createLight;
58454
+ const postprocess = options?.light?.postprocess;
58455
+ gltf.nodes.forEach((gltfNode, nodeIndex)=>{
58456
+ if (gltfNode.hasOwnProperty('extensions') && gltfNode.extensions.hasOwnProperty('KHR_lights_punctual') && gltfNode.extensions.KHR_lights_punctual.hasOwnProperty('light')) {
58457
+ const lightIndex = gltfNode.extensions.KHR_lights_punctual.light;
58458
+ const gltfLight = gltfLights[lightIndex];
58459
+ if (gltfLight) {
58460
+ if (preprocess) {
58461
+ preprocess(gltfLight);
58462
+ }
58463
+ const light = process(gltfLight, nodes[nodeIndex]);
58464
+ if (postprocess) {
58465
+ postprocess(gltfLight, light);
58466
+ }
58467
+ if (light) {
58468
+ if (!lights) lights = new Map();
58469
+ lights.set(gltfNode, light);
58470
+ }
58471
+ }
58472
+ }
58473
+ });
58474
+ }
58475
+ }
58476
+ return lights;
58477
+ };
58478
+ const linkSkins = (gltf, renders, skins)=>{
58479
+ gltf.nodes.forEach((gltfNode)=>{
58480
+ if (gltfNode.hasOwnProperty('mesh') && gltfNode.hasOwnProperty('skin')) {
58481
+ const meshGroup = renders[gltfNode.mesh].meshes;
58482
+ meshGroup.forEach((mesh)=>{
58483
+ mesh.skin = skins[gltfNode.skin];
58484
+ });
58485
+ }
58486
+ });
58487
+ };
58488
+ const createResources = async (device, gltf, bufferViews, textures, options)=>{
58489
+ const preprocess = options?.global?.preprocess;
58490
+ const postprocess = options?.global?.postprocess;
58491
+ if (preprocess) {
58492
+ preprocess(gltf);
58493
+ }
58494
+ if (gltf.asset && gltf.asset.generator === 'PlayCanvas') ;
58495
+ const nodeInstancingMap = new Map();
58496
+ const nodes = createNodes(gltf, options, nodeInstancingMap);
58497
+ const scenes = createScenes(gltf, nodes);
58498
+ const lights = createLights(gltf, nodes, options);
58499
+ const cameras = createCameras(gltf, nodes, options);
58500
+ const variants = createVariants(gltf);
58501
+ const bufferViewData = await Promise.all(bufferViews);
58502
+ const { meshes, meshVariants, meshDefaultMaterials, promises } = createMeshes(device, gltf, bufferViewData, options);
58503
+ const animations = createAnimations(gltf, nodes, bufferViewData, options);
58504
+ createInstancing(device, gltf, nodeInstancingMap, bufferViewData);
58505
+ const textureAssets = await Promise.all(textures);
58506
+ const textureInstances = textureAssets.map((t)=>t.resource);
58507
+ const materials = createMaterials(gltf, textureInstances, options);
58508
+ const skins = createSkins(device, gltf, nodes, bufferViewData);
58509
+ const renders = [];
58510
+ for(let i = 0; i < meshes.length; i++){
58511
+ renders[i] = new Render();
58512
+ renders[i].meshes = meshes[i];
58513
+ }
58514
+ linkSkins(gltf, renders, skins);
58515
+ const result = new GlbResources();
58516
+ result.gltf = gltf;
58517
+ result.nodes = nodes;
58518
+ result.scenes = scenes;
58519
+ result.animations = animations;
58520
+ result.textures = textureAssets;
58521
+ result.materials = materials;
58522
+ result.variants = variants;
58523
+ result.meshVariants = meshVariants;
58524
+ result.meshDefaultMaterials = meshDefaultMaterials;
58525
+ result.renders = renders;
58526
+ result.skins = skins;
58527
+ result.lights = lights;
58528
+ result.cameras = cameras;
58529
+ result.nodeInstancingMap = nodeInstancingMap;
58530
+ if (postprocess) {
58531
+ postprocess(gltf, result);
58532
+ }
58533
+ await Promise.all(promises);
58534
+ return result;
58535
+ };
58536
+ const applySampler = (texture, gltfSampler)=>{
58537
+ const getFilter = (filter, defaultValue)=>{
58538
+ switch(filter){
58539
+ case 9728:
58540
+ return FILTER_NEAREST;
58541
+ case 9729:
58542
+ return FILTER_LINEAR;
58543
+ case 9984:
58544
+ return FILTER_NEAREST_MIPMAP_NEAREST;
58545
+ case 9985:
58546
+ return FILTER_LINEAR_MIPMAP_NEAREST;
58547
+ case 9986:
58548
+ return FILTER_NEAREST_MIPMAP_LINEAR;
58549
+ case 9987:
58550
+ return FILTER_LINEAR_MIPMAP_LINEAR;
58551
+ default:
58552
+ return defaultValue;
58553
+ }
58554
+ };
58555
+ const getWrap = (wrap, defaultValue)=>{
58556
+ switch(wrap){
58557
+ case 33071:
58558
+ return ADDRESS_CLAMP_TO_EDGE;
58559
+ case 33648:
58560
+ return ADDRESS_MIRRORED_REPEAT;
58561
+ case 10497:
58562
+ return ADDRESS_REPEAT;
58563
+ default:
58564
+ return defaultValue;
58565
+ }
58566
+ };
58567
+ if (texture) {
58568
+ gltfSampler = gltfSampler ?? {};
58569
+ texture.minFilter = getFilter(gltfSampler.minFilter, FILTER_LINEAR_MIPMAP_LINEAR);
58570
+ texture.magFilter = getFilter(gltfSampler.magFilter, FILTER_LINEAR);
58571
+ texture.addressU = getWrap(gltfSampler.wrapS, ADDRESS_REPEAT);
58572
+ texture.addressV = getWrap(gltfSampler.wrapT, ADDRESS_REPEAT);
58573
+ }
58574
+ };
58575
+ let gltfTextureUniqueId = 0;
58576
+ const getTextureSource = (gltfTexture)=>gltfTexture.extensions?.KHR_texture_basisu?.source ?? gltfTexture.extensions?.EXT_texture_webp?.source ?? gltfTexture.source;
58577
+ const createImages = (gltf, bufferViews, urlBase, registry, options)=>{
58578
+ if (!gltf.images || gltf.images.length === 0) {
58579
+ return [];
58580
+ }
58581
+ const preprocess = options?.image?.preprocess;
58582
+ const processAsync = options?.image?.processAsync;
58583
+ const postprocess = options?.image?.postprocess;
58584
+ const mimeTypeFileExtensions = {
58585
+ 'image/png': 'png',
58586
+ 'image/jpeg': 'jpg',
58587
+ 'image/basis': 'basis',
58588
+ 'image/ktx': 'ktx',
58589
+ 'image/ktx2': 'ktx2',
58590
+ 'image/vnd-ms.dds': 'dds'
58591
+ };
58592
+ const getGammaTextures = (gltf)=>{
58593
+ const set = new Set();
58594
+ if (gltf.hasOwnProperty('materials')) {
58595
+ gltf.materials.forEach((gltfMaterial)=>{
58596
+ if (gltfMaterial.hasOwnProperty('pbrMetallicRoughness')) {
58597
+ const pbrData = gltfMaterial.pbrMetallicRoughness;
58598
+ if (pbrData.hasOwnProperty('baseColorTexture')) {
58599
+ const gltfTexture = gltf.textures[pbrData.baseColorTexture.index];
58600
+ set.add(getTextureSource(gltfTexture));
58601
+ }
58602
+ }
58603
+ if (gltfMaterial.hasOwnProperty('emissiveTexture')) {
58604
+ const gltfTexture = gltf.textures[gltfMaterial.emissiveTexture.index];
58605
+ set.add(getTextureSource(gltfTexture));
58606
+ }
58607
+ if (gltfMaterial.hasOwnProperty('extensions')) {
58608
+ const sheen = gltfMaterial.extensions.KHR_materials_sheen;
58609
+ if (sheen) {
58610
+ if (sheen.hasOwnProperty('sheenColorTexture')) {
58611
+ const gltfTexture = gltf.textures[sheen.sheenColorTexture.index];
58612
+ set.add(getTextureSource(gltfTexture));
58613
+ }
58614
+ }
58615
+ const specularGlossiness = gltfMaterial.extensions.KHR_materials_pbrSpecularGlossiness;
58616
+ if (specularGlossiness) {
58617
+ if (specularGlossiness.hasOwnProperty('specularGlossinessTexture')) {
58618
+ const gltfTexture = gltf.textures[specularGlossiness.specularGlossinessTexture.index];
58619
+ set.add(getTextureSource(gltfTexture));
58620
+ }
58621
+ }
58622
+ const specular = gltfMaterial.extensions.KHR_materials_specular;
58623
+ if (specular) {
58624
+ if (specular.hasOwnProperty('specularColorTexture')) {
58625
+ const gltfTexture = gltf.textures[specular.specularColorTexture.index];
58626
+ set.add(getTextureSource(gltfTexture));
58627
+ }
58628
+ }
58629
+ }
58630
+ });
58631
+ }
58632
+ return set;
58633
+ };
58634
+ const loadTexture = (gltfImage, url, bufferView, mimeType, options, srgb)=>{
58635
+ return new Promise((resolve, reject)=>{
58636
+ const continuation = (bufferViewData)=>{
58637
+ const name = `${gltfImage.name || 'gltf-texture'}-${gltfTextureUniqueId++}`;
58638
+ const file = {
58639
+ url: url || name
58640
+ };
58641
+ if (bufferViewData) {
58642
+ file.contents = bufferViewData.slice(0).buffer;
58643
+ }
58644
+ if (mimeType) {
58645
+ const extension = mimeTypeFileExtensions[mimeType];
58646
+ if (extension) {
58647
+ file.filename = `${file.url}.${extension}`;
58648
+ }
58649
+ }
58650
+ const data = {
58651
+ srgb
58652
+ };
58653
+ const asset = new Asset(name, 'texture', file, data, options);
58654
+ asset.on('load', (asset)=>resolve(asset));
58655
+ asset.on('error', (err)=>reject(err));
58656
+ registry.add(asset);
58657
+ registry.load(asset);
58658
+ };
58659
+ if (bufferView) {
58660
+ bufferView.then((bufferViewData)=>continuation(bufferViewData));
58661
+ } else {
58662
+ continuation(null);
58663
+ }
58664
+ });
58665
+ };
58666
+ const gammaTextures = getGammaTextures(gltf);
58667
+ return gltf.images.map((gltfImage, i)=>{
58668
+ if (preprocess) {
58669
+ preprocess(gltfImage);
58670
+ }
58671
+ let promise;
58672
+ if (processAsync) {
58673
+ promise = new Promise((resolve, reject)=>{
58674
+ processAsync(gltfImage, (err, textureAsset)=>{
58675
+ if (err) {
58676
+ reject(err);
58677
+ } else {
58678
+ resolve(textureAsset);
58679
+ }
58680
+ });
58681
+ });
58682
+ } else {
58683
+ promise = new Promise((resolve)=>{
58684
+ resolve(null);
58685
+ });
58686
+ }
58687
+ promise = promise.then((textureAsset)=>{
58688
+ const srgb = gammaTextures.has(i);
58689
+ if (textureAsset) {
58690
+ return textureAsset;
58691
+ } else if (gltfImage.hasOwnProperty('uri')) {
58692
+ if (isDataURI(gltfImage.uri)) {
58693
+ return loadTexture(gltfImage, gltfImage.uri, null, getDataURIMimeType(gltfImage.uri), null, srgb);
58694
+ }
58695
+ return loadTexture(gltfImage, ABSOLUTE_URL.test(gltfImage.uri) ? gltfImage.uri : path.join(urlBase, gltfImage.uri), null, null, {
58696
+ crossOrigin: 'anonymous'
58697
+ }, srgb);
58698
+ } else if (gltfImage.hasOwnProperty('bufferView') && gltfImage.hasOwnProperty('mimeType')) {
58699
+ return loadTexture(gltfImage, null, bufferViews[gltfImage.bufferView], gltfImage.mimeType, null, srgb);
58700
+ }
58701
+ return Promise.reject(new Error(`Invalid image found in gltf (neither uri or bufferView found). index=${i}`));
58702
+ });
58703
+ if (postprocess) {
58704
+ promise = promise.then((textureAsset)=>{
58705
+ postprocess(gltfImage, textureAsset);
58706
+ return textureAsset;
58707
+ });
58708
+ }
58709
+ return promise;
58710
+ });
58711
+ };
58712
+ const createTextures = (gltf, images, options)=>{
58713
+ if (!gltf?.images?.length || !gltf?.textures?.length) {
58714
+ return [];
58715
+ }
58716
+ const preprocess = options?.texture?.preprocess;
58717
+ const processAsync = options?.texture?.processAsync;
58718
+ const postprocess = options?.texture?.postprocess;
58719
+ const seenImages = new Set();
58720
+ return gltf.textures.map((gltfTexture)=>{
58721
+ if (preprocess) {
58722
+ preprocess(gltfTexture);
58723
+ }
58724
+ let promise;
58725
+ if (processAsync) {
58726
+ promise = new Promise((resolve, reject)=>{
58727
+ processAsync(gltfTexture, gltf.images, (err, gltfImageIndex)=>{
58728
+ if (err) {
58729
+ reject(err);
58730
+ } else {
58731
+ resolve(gltfImageIndex);
58732
+ }
58733
+ });
58734
+ });
58735
+ } else {
58736
+ promise = new Promise((resolve)=>{
58737
+ resolve(null);
58738
+ });
58739
+ }
58740
+ promise = promise.then((gltfImageIndex)=>{
58741
+ gltfImageIndex = gltfImageIndex ?? getTextureSource(gltfTexture);
58742
+ const cloneAsset = seenImages.has(gltfImageIndex);
58743
+ seenImages.add(gltfImageIndex);
58744
+ return images[gltfImageIndex].then((imageAsset)=>{
58745
+ const asset = cloneAsset ? cloneTextureAsset(imageAsset) : imageAsset;
58746
+ applySampler(asset.resource, (gltf.samplers ?? [])[gltfTexture.sampler]);
58747
+ return asset;
58748
+ });
58749
+ });
58750
+ if (postprocess) {
58751
+ promise = promise.then((textureAsset)=>{
58752
+ postprocess(gltfTexture, textureAsset);
58753
+ return textureAsset;
58754
+ });
58755
+ }
58756
+ return promise;
58757
+ });
58758
+ };
58759
+ const loadBuffers = (gltf, binaryChunk, urlBase, options)=>{
58760
+ if (!gltf.buffers || gltf.buffers.length === 0) {
58761
+ return [];
58762
+ }
58763
+ const preprocess = options?.buffer?.preprocess;
58764
+ const processAsync = options?.buffer?.processAsync;
58765
+ const postprocess = options?.buffer?.postprocess;
58766
+ return gltf.buffers.map((gltfBuffer, i)=>{
58767
+ if (preprocess) {
58768
+ preprocess(gltfBuffer);
58769
+ }
58770
+ let promise;
58771
+ if (processAsync) {
58772
+ promise = new Promise((resolve, reject)=>{
58773
+ processAsync(gltfBuffer, (err, arrayBuffer)=>{
58774
+ if (err) {
58775
+ reject(err);
58776
+ } else {
58777
+ resolve(arrayBuffer);
58778
+ }
58779
+ });
58780
+ });
58781
+ } else {
58782
+ promise = new Promise((resolve)=>{
58783
+ resolve(null);
58784
+ });
58785
+ }
58786
+ promise = promise.then((arrayBuffer)=>{
58787
+ if (arrayBuffer) {
58788
+ return arrayBuffer;
58789
+ } else if (gltfBuffer.hasOwnProperty('uri')) {
58790
+ if (isDataURI(gltfBuffer.uri)) {
58791
+ const byteString = atob(gltfBuffer.uri.split(',')[1]);
58792
+ const binaryArray = new Uint8Array(byteString.length);
58793
+ for(let j = 0; j < byteString.length; j++){
58794
+ binaryArray[j] = byteString.charCodeAt(j);
58795
+ }
58796
+ return binaryArray;
58797
+ }
58798
+ return new Promise((resolve, reject)=>{
58799
+ http.get(ABSOLUTE_URL.test(gltfBuffer.uri) ? gltfBuffer.uri : path.join(urlBase, gltfBuffer.uri), {
58800
+ cache: true,
58801
+ responseType: 'arraybuffer',
58802
+ retry: false
58803
+ }, (err, result)=>{
58804
+ if (err) {
58805
+ reject(err);
58806
+ } else {
58807
+ resolve(new Uint8Array(result));
58808
+ }
58809
+ });
58810
+ });
58811
+ }
58812
+ return binaryChunk;
58813
+ });
58814
+ if (postprocess) {
58815
+ promise = promise.then((buffer)=>{
58816
+ postprocess(gltf.buffers[i], buffer);
58817
+ return buffer;
58818
+ });
58819
+ }
58820
+ return promise;
58821
+ });
58822
+ };
58823
+ const parseGltf = (gltfChunk, callback)=>{
58824
+ const decodeBinaryUtf8 = (array)=>{
58825
+ if (typeof TextDecoder !== 'undefined') {
58826
+ return new TextDecoder().decode(array);
58827
+ }
58828
+ let str = '';
58829
+ for(let i = 0; i < array.length; i++){
58830
+ str += String.fromCharCode(array[i]);
58831
+ }
58832
+ return decodeURIComponent(escape(str));
58833
+ };
58834
+ const gltf = JSON.parse(decodeBinaryUtf8(gltfChunk));
58835
+ if (gltf.asset && gltf.asset.version && parseFloat(gltf.asset.version) < 2) {
58836
+ callback(`Invalid gltf version. Expected version 2.0 or above but found version '${gltf.asset.version}'.`);
58837
+ return;
58838
+ }
58839
+ callback(null, gltf);
58840
+ };
58841
+ const parseGlb = (glbData, callback)=>{
58842
+ const data = glbData instanceof ArrayBuffer ? new DataView(glbData) : new DataView(glbData.buffer, glbData.byteOffset, glbData.byteLength);
58843
+ const magic = data.getUint32(0, true);
58844
+ const version = data.getUint32(4, true);
58845
+ const length = data.getUint32(8, true);
58846
+ if (magic !== 0x46546C67) {
58847
+ callback(`Invalid magic number found in glb header. Expected 0x46546C67, found 0x${magic.toString(16)}`);
58848
+ return;
58849
+ }
58850
+ if (version !== 2) {
58851
+ callback(`Invalid version number found in glb header. Expected 2, found ${version}`);
58852
+ return;
58853
+ }
58854
+ if (length <= 0 || length > data.byteLength) {
58855
+ callback(`Invalid length found in glb header. Found ${length}`);
58856
+ return;
58857
+ }
58858
+ const chunks = [];
58859
+ let offset = 12;
58860
+ while(offset < length){
58861
+ const chunkLength = data.getUint32(offset, true);
58862
+ if (offset + chunkLength + 8 > data.byteLength) {
58863
+ callback(`Invalid chunk length found in glb. Found ${chunkLength}`);
58864
+ }
58865
+ const chunkType = data.getUint32(offset + 4, true);
58866
+ const chunkData = new Uint8Array(data.buffer, data.byteOffset + offset + 8, chunkLength);
58867
+ chunks.push({
58868
+ length: chunkLength,
58869
+ type: chunkType,
58870
+ data: chunkData
58871
+ });
58872
+ offset += chunkLength + 8;
58873
+ }
58874
+ if (chunks.length !== 1 && chunks.length !== 2) {
58875
+ callback('Invalid number of chunks found in glb file.');
58876
+ return;
58877
+ }
58878
+ if (chunks[0].type !== 0x4E4F534A) {
58879
+ callback(`Invalid chunk type found in glb file. Expected 0x4E4F534A, found 0x${chunks[0].type.toString(16)}`);
58880
+ return;
58881
+ }
58882
+ if (chunks.length > 1 && chunks[1].type !== 0x004E4942) {
58883
+ callback(`Invalid chunk type found in glb file. Expected 0x004E4942, found 0x${chunks[1].type.toString(16)}`);
58884
+ return;
58885
+ }
58886
+ callback(null, {
58887
+ gltfChunk: chunks[0].data,
58888
+ binaryChunk: chunks.length === 2 ? chunks[1].data : null
58889
+ });
58890
+ };
58891
+ const parseChunk = (filename, data, callback)=>{
58892
+ const hasGlbHeader = ()=>{
58893
+ const u8 = new Uint8Array(data);
58894
+ return u8[0] === 103 && u8[1] === 108 && u8[2] === 84 && u8[3] === 70;
58895
+ };
58896
+ if (filename && filename.toLowerCase().endsWith('.glb') || hasGlbHeader()) {
58897
+ parseGlb(data, callback);
58898
+ } else {
58899
+ callback(null, {
58900
+ gltfChunk: data,
58901
+ binaryChunk: null
58902
+ });
58903
+ }
58904
+ };
58905
+ const createBufferViews = (gltf, buffers, options)=>{
58906
+ const result = [];
58907
+ const preprocess = options?.bufferView?.preprocess;
58908
+ const processAsync = options?.bufferView?.processAsync;
58909
+ const postprocess = options?.bufferView?.postprocess;
58910
+ if (!gltf.bufferViews?.length) {
58911
+ return result;
58912
+ }
58913
+ for(let i = 0; i < gltf.bufferViews.length; ++i){
58914
+ const gltfBufferView = gltf.bufferViews[i];
58915
+ if (preprocess) {
58916
+ preprocess(gltfBufferView);
58917
+ }
58918
+ let promise;
58919
+ if (processAsync) {
58920
+ promise = new Promise((resolve, reject)=>{
58921
+ processAsync(gltfBufferView, buffers, (err, result)=>{
58922
+ if (err) {
58923
+ reject(err);
58924
+ } else {
58925
+ resolve(result);
58926
+ }
58927
+ });
58928
+ });
58929
+ } else {
58930
+ promise = new Promise((resolve)=>{
58931
+ resolve(null);
58932
+ });
58933
+ }
58934
+ promise = promise.then((buffer)=>{
58935
+ if (buffer) {
58936
+ return buffer;
58937
+ }
58938
+ return buffers[gltfBufferView.buffer].then((buffer)=>{
58939
+ return new Uint8Array(buffer.buffer, buffer.byteOffset + (gltfBufferView.byteOffset || 0), gltfBufferView.byteLength);
58940
+ });
58941
+ });
58942
+ if (gltfBufferView.hasOwnProperty('byteStride')) {
58943
+ promise = promise.then((typedArray)=>{
58944
+ typedArray.byteStride = gltfBufferView.byteStride;
58945
+ return typedArray;
58946
+ });
58947
+ }
58948
+ if (postprocess) {
58949
+ promise = promise.then((typedArray)=>{
58950
+ postprocess(gltfBufferView, typedArray);
58951
+ return typedArray;
58952
+ });
58953
+ }
58954
+ result.push(promise);
58955
+ }
58956
+ return result;
58957
+ };
58958
+ class GlbParser {
58959
+ static parse(filename, urlBase, data, device, registry, options, callback) {
58960
+ parseChunk(filename, data, (err, chunks)=>{
58961
+ if (err) {
58962
+ callback(err);
58963
+ return;
58964
+ }
58965
+ parseGltf(chunks.gltfChunk, (err, gltf)=>{
58966
+ if (err) {
58967
+ callback(err);
58968
+ return;
58969
+ }
58970
+ const buffers = loadBuffers(gltf, chunks.binaryChunk, urlBase, options);
58971
+ const bufferViews = createBufferViews(gltf, buffers, options);
58972
+ const images = createImages(gltf, bufferViews, urlBase, registry, options);
58973
+ const textures = createTextures(gltf, images, options);
58974
+ createResources(device, gltf, bufferViews, textures, options).then((result)=>callback(null, result)).catch((err)=>callback(err));
58975
+ });
58976
+ });
58977
+ }
58978
+ static createDefaultMaterial() {
58979
+ return createMaterial({
58980
+ name: 'defaultGlbMaterial'
58981
+ }, []);
58982
+ }
58983
+ }
58984
+
56026
58985
  class BinaryHandler extends ResourceHandler {
56027
58986
  load(url, callback) {
56028
58987
  if (typeof url === 'string') {
@@ -56051,6 +59010,346 @@ class BinaryHandler extends ResourceHandler {
56051
59010
  }
56052
59011
  }
56053
59012
 
59013
+ class GlbContainerResource {
59014
+ get model() {
59015
+ if (!this._model) {
59016
+ const model = GlbContainerResource.createModel(this.data, this._defaultMaterial);
59017
+ const modelAsset = GlbContainerResource.createAsset(this._assetName, 'model', model, 0);
59018
+ this._assets.add(modelAsset);
59019
+ this._model = modelAsset;
59020
+ }
59021
+ return this._model;
59022
+ }
59023
+ static createAsset(assetName, type, resource, index) {
59024
+ const subAsset = new Asset(`${assetName}/${type}/${index}`, type, {
59025
+ url: ''
59026
+ });
59027
+ subAsset.resource = resource;
59028
+ subAsset.loaded = true;
59029
+ return subAsset;
59030
+ }
59031
+ instantiateModelEntity(options) {
59032
+ const entity = new Entity(undefined, this._assets._loader._app);
59033
+ entity.addComponent('model', Object.assign({
59034
+ type: 'asset',
59035
+ asset: this.model
59036
+ }, options));
59037
+ return entity;
59038
+ }
59039
+ instantiateRenderEntity(options) {
59040
+ const defaultMaterial = this._defaultMaterial;
59041
+ const skinnedMeshInstances = [];
59042
+ const createMeshInstance = function(root, entity, mesh, materials, meshDefaultMaterials, skins, gltfNode, nodeInstancingMap) {
59043
+ const materialIndex = meshDefaultMaterials[mesh.id];
59044
+ const material = materialIndex === undefined ? defaultMaterial : materials[materialIndex];
59045
+ const meshInstance = new MeshInstance(mesh, material);
59046
+ if (mesh.morph) {
59047
+ meshInstance.morphInstance = new MorphInstance(mesh.morph);
59048
+ }
59049
+ if (gltfNode.hasOwnProperty('skin')) {
59050
+ skinnedMeshInstances.push({
59051
+ meshInstance: meshInstance,
59052
+ rootBone: root,
59053
+ entity: entity
59054
+ });
59055
+ }
59056
+ const instData = nodeInstancingMap.get(gltfNode);
59057
+ if (instData) {
59058
+ const matrices = instData.matrices;
59059
+ const vbFormat = VertexFormat.getDefaultInstancingFormat(mesh.device);
59060
+ const vb = new VertexBuffer(mesh.device, vbFormat, matrices.length / 16, {
59061
+ data: matrices
59062
+ });
59063
+ meshInstance.setInstancing(vb);
59064
+ meshInstance.instancingData._destroyVertexBuffer = true;
59065
+ }
59066
+ return meshInstance;
59067
+ };
59068
+ const cloneHierarchy = (root, node, glb)=>{
59069
+ const entity = new Entity(undefined, this._assets._loader._app);
59070
+ node._cloneInternal(entity);
59071
+ if (!root) root = entity;
59072
+ let attachedMi = null;
59073
+ let renderAsset = null;
59074
+ for(let i = 0; i < glb.nodes.length; i++){
59075
+ const glbNode = glb.nodes[i];
59076
+ if (glbNode === node) {
59077
+ const gltfNode = glb.gltf.nodes[i];
59078
+ if (gltfNode.hasOwnProperty('mesh')) {
59079
+ const meshGroup = glb.renders[gltfNode.mesh].meshes;
59080
+ renderAsset = this.renders[gltfNode.mesh];
59081
+ for(let mi = 0; mi < meshGroup.length; mi++){
59082
+ const mesh = meshGroup[mi];
59083
+ if (mesh) {
59084
+ const cloneMi = createMeshInstance(root, entity, mesh, glb.materials, glb.meshDefaultMaterials, glb.skins, gltfNode, glb.nodeInstancingMap);
59085
+ if (!attachedMi) {
59086
+ attachedMi = [];
59087
+ }
59088
+ attachedMi.push(cloneMi);
59089
+ }
59090
+ }
59091
+ }
59092
+ if (glb.lights) {
59093
+ const lightEntity = glb.lights.get(gltfNode);
59094
+ if (lightEntity) {
59095
+ entity.addChild(lightEntity.clone());
59096
+ }
59097
+ }
59098
+ if (glb.cameras) {
59099
+ const cameraEntity = glb.cameras.get(gltfNode);
59100
+ if (cameraEntity) {
59101
+ cameraEntity.camera.system.cloneComponent(cameraEntity, entity);
59102
+ }
59103
+ }
59104
+ }
59105
+ }
59106
+ if (attachedMi) {
59107
+ entity.addComponent('render', Object.assign({
59108
+ type: 'asset',
59109
+ meshInstances: attachedMi
59110
+ }, options));
59111
+ entity.render.assignAsset(renderAsset);
59112
+ }
59113
+ const children = node.children;
59114
+ for(let i = 0; i < children.length; i++){
59115
+ const childClone = cloneHierarchy(root, children[i], glb);
59116
+ entity.addChild(childClone);
59117
+ }
59118
+ return entity;
59119
+ };
59120
+ const sceneClones = [];
59121
+ for (const scene of this.data.scenes){
59122
+ sceneClones.push(cloneHierarchy(null, scene, this.data));
59123
+ }
59124
+ skinnedMeshInstances.forEach((data)=>{
59125
+ data.meshInstance.skinInstance = SkinInstanceCache.createCachedSkinInstance(data.meshInstance.mesh.skin, data.rootBone, data.entity);
59126
+ data.meshInstance.node.render.rootBone = data.rootBone;
59127
+ });
59128
+ return GlbContainerResource.createSceneHierarchy(sceneClones, Entity);
59129
+ }
59130
+ getMaterialVariants() {
59131
+ return this.data.variants ? Object.keys(this.data.variants) : [];
59132
+ }
59133
+ applyMaterialVariant(entity, name) {
59134
+ const variant = name ? this.data.variants[name] : null;
59135
+ if (variant === undefined) {
59136
+ return;
59137
+ }
59138
+ const renders = entity.findComponents('render');
59139
+ for(let i = 0; i < renders.length; i++){
59140
+ const renderComponent = renders[i];
59141
+ this._applyMaterialVariant(variant, renderComponent.meshInstances);
59142
+ }
59143
+ }
59144
+ applyMaterialVariantInstances(instances, name) {
59145
+ const variant = name ? this.data.variants[name] : null;
59146
+ if (variant === undefined) {
59147
+ return;
59148
+ }
59149
+ this._applyMaterialVariant(variant, instances);
59150
+ }
59151
+ _applyMaterialVariant(variant, instances) {
59152
+ instances.forEach((instance)=>{
59153
+ if (variant === null) {
59154
+ instance.material = this._defaultMaterial;
59155
+ } else {
59156
+ const meshVariants = this.data.meshVariants[instance.mesh.id];
59157
+ if (meshVariants) {
59158
+ instance.material = this.data.materials[meshVariants[variant]];
59159
+ }
59160
+ }
59161
+ });
59162
+ }
59163
+ static createSceneHierarchy(sceneNodes, nodeType) {
59164
+ let root = null;
59165
+ if (sceneNodes.length === 1) {
59166
+ root = sceneNodes[0];
59167
+ } else {
59168
+ root = new nodeType('SceneGroup');
59169
+ for (const scene of sceneNodes){
59170
+ root.addChild(scene);
59171
+ }
59172
+ }
59173
+ return root;
59174
+ }
59175
+ static createModel(glb, defaultMaterial) {
59176
+ const createMeshInstance = function(model, mesh, skins, skinInstances, materials, node, gltfNode) {
59177
+ const materialIndex = glb.meshDefaultMaterials[mesh.id];
59178
+ const material = materialIndex === undefined ? defaultMaterial : materials[materialIndex];
59179
+ const meshInstance = new MeshInstance(mesh, material, node);
59180
+ if (mesh.morph) {
59181
+ const morphInstance = new MorphInstance(mesh.morph);
59182
+ meshInstance.morphInstance = morphInstance;
59183
+ model.morphInstances.push(morphInstance);
59184
+ }
59185
+ if (gltfNode.hasOwnProperty('skin')) {
59186
+ const skinIndex = gltfNode.skin;
59187
+ const skin = skins[skinIndex];
59188
+ mesh.skin = skin;
59189
+ const skinInstance = skinInstances[skinIndex];
59190
+ meshInstance.skinInstance = skinInstance;
59191
+ model.skinInstances.push(skinInstance);
59192
+ }
59193
+ model.meshInstances.push(meshInstance);
59194
+ };
59195
+ const model = new Model();
59196
+ const skinInstances = [];
59197
+ for (const skin of glb.skins){
59198
+ const skinInstance = new SkinInstance(skin);
59199
+ skinInstance.bones = skin.bones;
59200
+ skinInstances.push(skinInstance);
59201
+ }
59202
+ model.graph = GlbContainerResource.createSceneHierarchy(glb.scenes, GraphNode);
59203
+ for(let i = 0; i < glb.nodes.length; i++){
59204
+ const node = glb.nodes[i];
59205
+ if (node.root === model.graph) {
59206
+ const gltfNode = glb.gltf.nodes[i];
59207
+ if (gltfNode.hasOwnProperty('mesh')) {
59208
+ const meshGroup = glb.renders[gltfNode.mesh].meshes;
59209
+ for(let mi = 0; mi < meshGroup.length; mi++){
59210
+ const mesh = meshGroup[mi];
59211
+ if (mesh) {
59212
+ createMeshInstance(model, mesh, glb.skins, skinInstances, glb.materials, node, gltfNode);
59213
+ }
59214
+ }
59215
+ }
59216
+ }
59217
+ }
59218
+ return model;
59219
+ }
59220
+ destroy() {
59221
+ const registry = this._assets;
59222
+ const destroyAsset = function(asset) {
59223
+ registry.remove(asset);
59224
+ asset.unload();
59225
+ };
59226
+ const destroyAssets = function(assets) {
59227
+ assets.forEach((asset)=>{
59228
+ destroyAsset(asset);
59229
+ });
59230
+ };
59231
+ if (this.animations) {
59232
+ destroyAssets(this.animations);
59233
+ this.animations = null;
59234
+ }
59235
+ if (this.textures) {
59236
+ destroyAssets(this.textures);
59237
+ this.textures = null;
59238
+ }
59239
+ if (this.materials) {
59240
+ destroyAssets(this.materials);
59241
+ this.materials = null;
59242
+ }
59243
+ if (this.renders) {
59244
+ destroyAssets(this.renders);
59245
+ this.renders = null;
59246
+ }
59247
+ if (this._model) {
59248
+ destroyAsset(this._model);
59249
+ this._model = null;
59250
+ }
59251
+ this.data = null;
59252
+ this.assets = null;
59253
+ }
59254
+ constructor(data, asset, assets, defaultMaterial){
59255
+ const createAsset = function(type, resource, index) {
59256
+ const subAsset = GlbContainerResource.createAsset(asset.name, type, resource, index);
59257
+ assets.add(subAsset);
59258
+ return subAsset;
59259
+ };
59260
+ const renders = [];
59261
+ for(let i = 0; i < data.renders.length; ++i){
59262
+ renders.push(createAsset('render', data.renders[i], i));
59263
+ }
59264
+ const materials = [];
59265
+ for(let i = 0; i < data.materials.length; ++i){
59266
+ materials.push(createAsset('material', data.materials[i], i));
59267
+ }
59268
+ const animations = [];
59269
+ for(let i = 0; i < data.animations.length; ++i){
59270
+ animations.push(createAsset('animation', data.animations[i], i));
59271
+ }
59272
+ this.data = data;
59273
+ this._model = null;
59274
+ this._assetName = asset.name;
59275
+ this._assets = assets;
59276
+ this._defaultMaterial = defaultMaterial;
59277
+ this.renders = renders;
59278
+ this.materials = materials;
59279
+ this.textures = data.textures;
59280
+ this.animations = animations;
59281
+ }
59282
+ }
59283
+
59284
+ class GlbContainerParser {
59285
+ _getUrlWithoutParams(url) {
59286
+ return url.indexOf('?') >= 0 ? url.split('?')[0] : url;
59287
+ }
59288
+ load(url, callback, asset) {
59289
+ Asset.fetchArrayBuffer(url.load, (err, result)=>{
59290
+ if (err) {
59291
+ callback(err);
59292
+ } else {
59293
+ GlbParser.parse(this._getUrlWithoutParams(url.original), path.extractPath(url.load), result, this._device, asset.registry, asset.options, (err, result)=>{
59294
+ if (err) {
59295
+ callback(err);
59296
+ } else {
59297
+ callback(null, new GlbContainerResource(result, asset, this._assets, this._defaultMaterial));
59298
+ }
59299
+ });
59300
+ }
59301
+ }, asset, this.maxRetries);
59302
+ }
59303
+ open(url, data, asset) {
59304
+ return data;
59305
+ }
59306
+ patch(asset, assets) {}
59307
+ constructor(device, assets, maxRetries){
59308
+ this._device = device;
59309
+ this._assets = assets;
59310
+ this._defaultMaterial = GlbParser.createDefaultMaterial();
59311
+ this.maxRetries = maxRetries;
59312
+ }
59313
+ }
59314
+
59315
+ class ContainerHandler extends ResourceHandler {
59316
+ set maxRetries(value) {
59317
+ this.glbContainerParser.maxRetries = value;
59318
+ for(const parser in this.parsers){
59319
+ if (this.parsers.hasOwnProperty(parser)) {
59320
+ this.parsers[parser].maxRetries = value;
59321
+ }
59322
+ }
59323
+ }
59324
+ get maxRetries() {
59325
+ return this.glbContainerParser.maxRetries;
59326
+ }
59327
+ _getUrlWithoutParams(url) {
59328
+ return url.indexOf('?') >= 0 ? url.split('?')[0] : url;
59329
+ }
59330
+ _getParser(url) {
59331
+ const ext = url ? path.getExtension(this._getUrlWithoutParams(url)).toLowerCase().replace('.', '') : null;
59332
+ return this.parsers[ext] || this.glbContainerParser;
59333
+ }
59334
+ load(url, callback, asset) {
59335
+ if (typeof url === 'string') {
59336
+ url = {
59337
+ load: url,
59338
+ original: url
59339
+ };
59340
+ }
59341
+ this._getParser(url.original).load(url, callback, asset);
59342
+ }
59343
+ open(url, data, asset) {
59344
+ return this._getParser(url).open(url, data, asset);
59345
+ }
59346
+ constructor(app){
59347
+ super(app, 'container');
59348
+ this.glbContainerParser = new GlbContainerParser(app.graphicsDevice, app.assets, 0);
59349
+ this.parsers = {};
59350
+ }
59351
+ }
59352
+
56054
59353
  const SH_C0 = 0.28209479177387814;
56055
59354
  class SplatCompressedIterator {
56056
59355
  constructor(gsplatData, p, r, s, c, sh){
@@ -65906,6 +69205,7 @@ class App extends AppBase {
65906
69205
  ScriptComponentSystem
65907
69206
  ];
65908
69207
  appOptions.resourceHandlers = [
69208
+ ContainerHandler,
65909
69209
  TextureHandler,
65910
69210
  GSplatHandler,
65911
69211
  BinaryHandler
@@ -68274,12 +71574,21 @@ class Viewer {
68274
71574
  cameraManager;
68275
71575
  annotations;
68276
71576
  forceRenderNextFrame = false;
71577
+ origChunks;
68277
71578
  constructor(global, gsplatLoad, skyboxLoad) {
68278
71579
  this.global = global;
68279
71580
  const { app, settings, config, events, state, camera } = global;
68280
71581
  const { graphicsDevice } = app;
68281
71582
  // enable anonymous CORS for image loading in safari
68282
71583
  app.loader.getHandler('texture').imgParser.crossOrigin = 'anonymous';
71584
+ this.origChunks = {
71585
+ glsl: {
71586
+ gsplatOutputVS: ShaderChunks.get(graphicsDevice, 'glsl').get('gsplatOutputVS')
71587
+ },
71588
+ wgsl: {
71589
+ gsplatOutputVS: ShaderChunks.get(graphicsDevice, 'wgsl').get('gsplatOutputVS')
71590
+ }
71591
+ };
68283
71592
  // render skybox as plain equirect
68284
71593
  const glsl = ShaderChunks.get(graphicsDevice, 'glsl');
68285
71594
  glsl.set('skyboxPS', glsl.get('skyboxPS').replace('mapRoughnessUv(uv, mipLevel)', 'uv'));
@@ -68513,6 +71822,11 @@ class Viewer {
68513
71822
  this.cameraFrame.destroy();
68514
71823
  this.cameraFrame = null;
68515
71824
  }
71825
+ // restore gsplat output shader chunks to engine defaults
71826
+ ShaderChunks.get(app.graphicsDevice, 'glsl').set('gsplatOutputVS', this.origChunks.glsl.gsplatOutputVS);
71827
+ ShaderChunks.get(app.graphicsDevice, 'wgsl').set('gsplatOutputVS', this.origChunks.wgsl.gsplatOutputVS);
71828
+ // restore original isColorBufferSrgb behavior
71829
+ RenderTarget.prototype.isColorBufferSrgb = origIsColorBufferSrgb;
68516
71830
  if (!app.xr.active) {
68517
71831
  camera.camera.toneMapping = tonemapTable[settings.tonemapping];
68518
71832
  camera.camera.clearColor = new Color(background.color);
@@ -69405,13 +72719,21 @@ const initXr = (global) => {
69405
72719
  if (app.xr.type === 'immersive-ar') {
69406
72720
  camera.camera.clearColor = clearColor;
69407
72721
  }
72722
+ // Restore the canvas to the correct position in the DOM after exiting XR. In
72723
+ // some browsers (e.g. Chrome on Android) the canvas is moved to a new root
72724
+ // during XR, and needs to be moved back on exit.
72725
+ requestAnimationFrame(() => {
72726
+ document.body.prepend(app.graphicsDevice.canvas);
72727
+ app.renderNextFrame = true;
72728
+ });
69408
72729
  });
69409
- events.on('startAR', () => {
69410
- app.xr.start(app.root.findComponent('camera'), 'immersive-ar', 'local-floor');
69411
- });
69412
- events.on('startVR', () => {
69413
- app.xr.start(app.root.findComponent('camera'), 'immersive-vr', 'local-floor');
69414
- });
72730
+ const start = (type) => {
72731
+ camera.camera.nearClip = 0.01;
72732
+ camera.camera.farClip = 1000;
72733
+ app.xr.start(app.root.findComponent('camera'), type, 'local-floor');
72734
+ };
72735
+ events.on('startAR', () => start('immersive-ar'));
72736
+ events.on('startVR', () => start('immersive-vr'));
69415
72737
  events.on('inputEvent', (event) => {
69416
72738
  if (event === 'cancel' && app.xr.active) {
69417
72739
  app.xr.end();
@@ -69419,7 +72741,7 @@ const initXr = (global) => {
69419
72741
  });
69420
72742
  };
69421
72743
 
69422
- var version = "1.14.0";
72744
+ var version = "1.14.1";
69423
72745
 
69424
72746
  const loadGsplat = async (app, config, progressCallback) => {
69425
72747
  const { contents, contentUrl, unified, aa } = config;
@@ -69488,6 +72810,9 @@ const createApp = async (canvas, config) => {
69488
72810
  xrCompatible: !config.webgpu,
69489
72811
  powerPreference: 'high-performance'
69490
72812
  });
72813
+ // Set maxPixelRatio so the XR framebuffer scale factor is computed correctly.
72814
+ // Regular rendering bypasses maxPixelRatio via the custom initCanvas sizing.
72815
+ device.maxPixelRatio = window.devicePixelRatio;
69491
72816
  // Create the application
69492
72817
  const app = new App(canvas, {
69493
72818
  graphicsDevice: device,
@@ -69503,10 +72828,11 @@ const createApp = async (canvas, config) => {
69503
72828
  const light = new Entity('light');
69504
72829
  light.setEulerAngles(35, 45, 0);
69505
72830
  light.addComponent('light', {
69506
- color: new Color(1, 1, 1),
69507
- intensity: 1.5
72831
+ color: new Color(1.0, 0.98, 0.957),
72832
+ intensity: 1
69508
72833
  });
69509
72834
  app.root.addChild(light);
72835
+ app.scene.ambientLight.set(0.51, 0.55, 0.65);
69510
72836
  return { app, camera };
69511
72837
  };
69512
72838
  // initialize canvas size and resizing
@@ -69525,6 +72851,10 @@ const initCanvas = (global) => {
69525
72851
  deviceSize.height = height * ratio;
69526
72852
  };
69527
72853
  const apply = () => {
72854
+ // don't resize the canvas during XR - the XR system manages its own framebuffers
72855
+ // and resetting canvas dimensions can invalidate the XRWebGLLayer
72856
+ if (app.xr?.active)
72857
+ return;
69528
72858
  const s = state.hqMode ? 1.0 : 0.5;
69529
72859
  const w = Math.ceil(deviceSize.width * s);
69530
72860
  const h = Math.ceil(deviceSize.height * s);