-
Notifications
You must be signed in to change notification settings - Fork 22
/
three.tgxloader.js
4018 lines (3450 loc) · 129 KB
/
three.tgxloader.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Sources
// https://www.bungie.net/sharedbundle/spasm
// http://www.gdcvault.com/play/1020412/Building-Customizable-Characters-for-Bungie
// http://advances.realtimerendering.com/destiny/siggraph2014/
// http://advances.realtimerendering.com/destiny/gdc_2017/
// @codekit-append "three.tgxutils.js";
// @codekit-append "three.tgxloader.js";
// @codekit-append "three.tgxmaterial.js";
// @codekit-append "three.tgxmanifest.js";
THREE.TGXLoaderUtils = (function() {
var scope = {
// https://www.khronos.org/opengl/wiki/Normalized_Integer
unormalize: function(value, bits) {
var max = Math.pow(2, bits) - 1;
return value/max;
},
normalize: function(value, bits) {
var max = Math.pow(2, bits-1) - 1;
return Math.max(value/max, -1);
},
byte: function(data, offset) {
return scope.decodeSigned(data, offset, 1);
},
ubyte: function(data, offset) {
return scope.decodeUnsigned(data, offset, 1);
},
short: function(data, offset) {
return scope.decodeSigned(data, offset, 2);
},
ushort: function(data, offset) {
return scope.decodeUnsigned(data, offset, 2);
},
int: function(data, offset) {
return scope.decodeSigned(data, offset, 4);
},
uint: function(data, offset) {
return scope.decodeUnsigned(data, offset, 4);
},
float: function(data, offset) {
return scope.decodeFloat(scope.bytes(data, offset, 4), 1, 8, 23, -126, 127);
},
bytes: function(data, offset, length) {
var bytes = [];
for (var i=0; i<length; i++) {
bytes.push(scope.ubyte(data, offset+i));
}
return bytes;
},
string: function(data, offset, length) {
var str = '';
if (offset == undefined) offset = 0;
if (length == undefined) length = data.length-offset;
for (var i=0; i<length; i++) {
var chr = data[offset+i];
if (chr == 0) continue;
str += String.fromCharCode(chr);
}
//var str = data.substr(offset, length);
//if (str.indexOf("\0") != -1) str = str.substr(0, str.indexOf("\0"));
return str;
},
bits: function(value, length) {
var str = '';
for (var i=0; i<length; i++) {
str = ((value >> i) & 0x1)+str;
}
return str;
},
radianToDegrees: function(value) {
return value * 180 / Math.PI;
},
degreesToRadian: function(value) {
return value * Math.PI / 180;
},
padNum: function(num, length) {
num = num.toString();
while(num.length < length) {
num = '0'+num;
}
return num;
},
decodeHex: function(data, offset, length) {
var hex = '';
if (typeof data == 'number') {
length = offset != undefined ? offset : 4;
for (var i=0; i<length; i++) {
var u8 = (data >> (i*8)) & 0xFF;
hex = scope.padNum(u8.toString(16), 2).toUpperCase() + hex;
}
return '0x'+hex;
}
if (offset == undefined) offset = 0;
if (length == undefined) length = data.length;
for (var i=0; i<length; i++) {
hex = scope.padNum(data.charCodeAt(offset+i).toString(16).toUpperCase(), 2) + hex;
}
return '0x'+hex;
},
decodeUnsigned: function(data, offset, length) {
var int = 0;
for (var i=0; i<length; i++) {
int |= data[offset+i] << (i*8);
}
return int;
},
decodeSigned: function(data, offset, length) {
if (typeof data != 'number') data = scope.decodeUnsigned(data, offset, length);
else length = offset;
var bits = length * 8;
var max = (1 << bits) - 1;
if (data & (1 << (bits - 1))) {
data = (data & max) - max;
}
return data;
},
decodeFloat: function(bytes, signBits, exponentBits, fractionBits, eMin, eMax, littleEndian) {
if (littleEndian == undefined) littleEndian = true;
var totalBits = (signBits + exponentBits + fractionBits);
var binary = "";
for (var i = 0, l = bytes.length; i < l; i++) {
var bits = bytes[i].toString(2);
while (bits.length < 8)
bits = "0" + bits;
if (littleEndian)
binary = bits + binary;
else
binary += bits;
}
var sign = (binary.charAt(0) == '1')?-1:1;
var exponent = parseInt(binary.substr(signBits, exponentBits), 2) - eMax;
var significandBase = binary.substr(signBits + exponentBits, fractionBits);
var significandBin = '1'+significandBase;
var i = 0;
var val = 1;
var significand = 0;
if (exponent == -eMax) {
if (significandBase.indexOf('1') == -1)
return 0;
else {
exponent = eMin;
significandBin = '0'+significandBase;
}
}
while (i < significandBin.length) {
significand += val * parseInt(significandBin.charAt(i));
val = val / 2;
i++;
}
return sign * significand * Math.pow(2, exponent);
}
};
return scope;
})();
// This is a copy of THREE.FileLoader with some extra settings applied to the XMLHttpRequest
// Was getting this error when trying to apply it to a standard THREE.FileLoader
// Error: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED.
THREE.BungieNetLoader = function(manager) {
this.manager = (manager !== undefined) ? manager : THREE.DefaultLoadingManager;
};
Object.assign(THREE.BungieNetLoader.prototype, {
load: function (url, apiKey, onLoad, onProgress, onError ) {
if ( url === undefined ) url = '';
if ( this.path !== undefined ) url = this.path + url;
var scope = this;
var cached = THREE.Cache.get( url );
if ( cached !== undefined ) {
scope.manager.itemStart( url );
setTimeout( function () {
if ( onLoad ) onLoad( cached );
scope.manager.itemEnd( url );
}, 0 );
return cached;
}
var request = new XMLHttpRequest();
request.open( 'GET', url, true );
// If an API Key is supplied, add it to the request header
// otherwise assume we want binary data
if (typeof apiKey == 'string') request.setRequestHeader('X-API-Key', apiKey);
if (url.indexOf('geometry') != -1) request.responseType = 'arraybuffer';
request.addEventListener( 'load', function ( event ) {
var response = event.target.response;
THREE.Cache.add( url, response );
if ( this.status === 200 ) {
if ( onLoad ) onLoad( response );
scope.manager.itemEnd( url );
} else if ( this.status === 0 ) {
// Some browsers return HTTP Status 0 when using non-http protocol
// e.g. 'file://' or 'data://'. Handle as success.
console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
if ( onLoad ) onLoad( response );
scope.manager.itemEnd( url );
} else {
if ( onError ) onError( event );
scope.manager.itemError( url );
}
}, false );
if ( onProgress !== undefined ) {
request.addEventListener( 'progress', function ( event ) {
onProgress( event );
}, false );
}
request.addEventListener( 'error', function ( event ) {
if ( onError ) onError( event );
scope.manager.itemError( url );
}, false );
if ( this.responseType !== undefined ) request.responseType = this.responseType;
if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials;
if ( request.overrideMimeType ) request.overrideMimeType( this.mimeType !== undefined ? this.mimeType : 'text/plain' );
request.send( null );
scope.manager.itemStart( url );
return request;
}
});
THREE.TGXLoader = function (manager) {
this.manager = (manager !== undefined) ? manager : THREE.DefaultLoadingManager;
};
// Global defaults
THREE.TGXLoader.APIKey = null;
THREE.TGXLoader.APIBasepath = 'https://www.bungie.net/d1/Platform/Destiny';
THREE.TGXLoader.Basepath = 'https://www.bungie.net';
THREE.TGXLoader.Platform = 'web';
THREE.TGXLoader.ManifestPath = null;
THREE.TGXLoader.DefaultAnimationPath = 'destiny_player_animation.js';
THREE.TGXLoader.Game = 'destiny';
THREE.TGXLoader.NoCache = false;
THREE.TGXLoader.EnvMapPath = null;
// Destiny 2
THREE.TGXLoader.APIBasepath2 = 'https://www.bungie.net/Platform/Destiny2';
THREE.TGXLoader.ManifestPath2 = null;
Object.assign(THREE.TGXLoader.prototype, {
load: function(options, onLoad, onProgress, onError) {
var defaultOptions = {
//itemHash: options,
itemHashes: [options],
shaderHash: 0,
ornamentHash: 0,
classHash: 0,
isFemale: false,
apiKey: THREE.TGXLoader.APIKey,
//apiBasepath: THREE.TGXLoader.APIBasepath,
basepath: THREE.TGXLoader.Basepath,
platform: THREE.TGXLoader.Platform,
//manifestPath: THREE.TGXLoader.ManifestPath,
loadTextures: true,
loadSkeleton: false,
loadAnimation: false,
animationPath: THREE.TGXLoader.DefaultAnimationPath,
game: THREE.TGXLoader.Game,
noCache: THREE.TGXLoader.NoCache,
envMapPath: THREE.TGXLoader.EnvMapPath,
ignoreLockedDyes: false,
debugMode: false
};
if (typeof options != 'object') options = {};
var game = options.game ? options.game : defaultOptions.game;
switch(game) {
case 'destiny2':
defaultOptions.apiBasepath = THREE.TGXLoader.APIBasepath2;
defaultOptions.manifestPath = THREE.TGXLoader.ManifestPath2;
break;
default:
defaultOptions.apiBasepath = THREE.TGXLoader.APIBasepath;
defaultOptions.manifestPath = THREE.TGXLoader.ManifestPath;
break;
}
for (var key in defaultOptions) {
if (options[key] === undefined) options[key] = defaultOptions[key];
}
if (options.itemHash != undefined) options.itemHashes = [options.itemHash];
console.log('Loader', options);
var scope = this;
//if (onProgress === undefined) {
// onProgress = function(event) {
// console.log(event);
// }
//}
if (onError === undefined) {
onError = function(error) {
console.error(error);
};
}
var url, loader, loadedCount = 0, loadedTotal = 0, items = [], shaderHashes = [], shaders = {};
// Mobile manifest support
if (options.platform == 'mobile' && !options.manifestPath && !THREE.TGXManifest.isCapable()) {
options.platform = 'web';
}
function assetsLoaded() {
if (loadedCount == loadedTotal) {
for (var i=0; i<items.length; i++) {
var item = items[i];
item.shaderHash = shaderHashes[i];
}
scope.parse(items, shaders, options, onLoad, onProgress, onError);
}
}
function itemAsset(itemIndex, itemHash) {
gearAsset(itemHash, function(item) {
//console.log('LoadedItem['+itemIndex+']', item);
items[itemIndex] = item;
});
}
function shaderAsset(itemIndex, shaderHash) {
shaderHashes[itemIndex] = shaderHash;
if (shaderHash == 0 || shaders[shaderHash] != undefined) {
loadedCount++;
assetsLoaded();
return;
}
shaders[shaderHash] = null;
gearAsset(shaderHash, function(shader) {
//console.log('LoadedShader['+itemIndex+']', shader);
shaders[shaderHash] = shader;
});
}
function gearAsset(/*itemIndex*/itemHash, callback) {
//var itemHash = options.itemHashes[itemIndex];
if (options.platform == 'mobile') {
if (options.manifestPath) { // Load manifest server-side
var url = options.manifestPath.replace('$itemHash', itemHash);
loader = new THREE.BungieNetLoader(this.manager);
loader.load(url, options.apiKey, function(response) {
loadedCount++;
try { // Invalid JSON response
response = JSON.parse(response);
//items[itemIndex] = response;
callback(response);
} catch(e) {
console.error('Invalid JSON', url);
}
assetsLoaded();
}, onProgress, onError);
} else { // Load manifest locally
var manifest = THREE.TGXLoader.Manifest;
if (!THREE.TGXLoader.Manifest) {
THREE.TGXLoader.Manifest = manifest = new THREE.TGXManifest(this.manager, options);
}
manifest.getAsset(itemHash, function(data) {
//items.push(data);
loadedCount++;
callback(data);
assetsLoaded();
}, onProgress, onError);
}
return;
}
// Web version support
url = options.apiBasepath+'/Manifest/22/'+itemHash+'/'; // GetDestinySingleDefinition
loader = new THREE.BungieNetLoader(this.manager);
loader.load(url, options.apiKey, function (response) {
loadedCount++;
try { // Invalid JSON response
response = JSON.parse(response);
} catch(e) {
console.error('Invalid JSON', url);
}
if (response.ErrorCode == 1) {
//items[itemIndex] = response.Response.data;
callback(response.Response.data);
} else {
console.error('Bungie Error Response', response);
}
assetsLoaded();
}, onProgress, onError);
}
loadedTotal = options.itemHashes.length*2;
// Only load the single ornamentHash when there is only one item
var defaultOrnamentHash = options.itemHashes.length == 1 ? options.ornamentHash : 0;
for (var i=0; i<options.itemHashes.length; i++) {
var itemHash = options.itemHashes[i];
var ornamentHash = options.ornamentHashes && i<options.ornamentHashes.length ? options.ornamentHashes[i] : defaultOrnamentHash;
var shaderHash = options.shaderHashes && i < options.shaderHashes.length ? options.shaderHashes[i] : options.shaderHash;
//console.log('Item['+i+']', options.itemHashes[i], 'Shader', shaderHash);
itemAsset(i, ornamentHash ? ornamentHash : itemHash);
shaderAsset(i, shaderHash);
}
},
//parse: (function() {
parse: function(items, shaders, options, onLoad, onProgress, onError) {
var utils = THREE.TGXLoaderUtils;
var game = options.game;
var basepath = options.basepath;
var contentpath = basepath+'/common/'+game+'_content';
var platform = options.platform;
var animationPath = options.animationPath;
var isFemale = options.isFemale;
var classHash = options.classHash;
var loadSkeleton = options.loadSkeleton;
var loadAnimation = options.loadAnimation;
var loadTextures = options.loadTextures;
var noCache = options.noCache;
var onLoadCallback = onLoad;
var onProgressCallback = onProgress;
var onErrorCallback = onError;
var ignoreLockedDyes = options.ignoreLockedDyes;
var debugMode = options.debugMode;
var contentLoaded = {
items: items,
regions: {},
gear: {},
tgxms: {
geometry: {},
textures: {}
},
geometry: {},
textures: {},
platedTextures: {},
mobileTextures: {},
skeleton: null,
animations: []
};
var assetLoadCount = 0;
var assetLoadTotal = 0;
var contentParsed = false;
// Rendering
var hasBones = false;
var defaultMaterial, geometry, materials;
var vertexOffset = 0;
// Missing Textures
var DEFAULT_CUBEMAP = '2164797681_default_monocrome_cubemap'/*'env_0'*/;
// Spasm.TGXAssetLoader.prototype.onLoadAssetManifest
function loadAssetManifest(gear) {
console.log('GearAsset', gear);
if (!gear.gearAsset) {
console.warn('MissingGearAsset', gear);
return;
}
var gearAsset = gear.gearAsset;
contentLoaded.regions[gear.requestedId] = [];
// Tally up gear resources for loading
assetLoadTotal += Object.keys(gearAsset.gear).length;
if (loadSkeleton) assetLoadTotal++;
if (loadAnimation) assetLoadTotal++;
for (var i=0; i<gearAsset.content.length; i++) {
var content = gearAsset.content[i];
console.log('Content['+i+']', content);
var contentRegions = loadAssetManifestContent(content);
contentLoaded.regions[gear.requestedId][i] = contentRegions;
}
// Load Gear
for (var gearIndex in gearAsset.gear) {
(function(gearIndex) {
var gearUrl = contentpath+'/geometry/gear/'+gearAsset.gear[gearIndex];
loadPart(gearUrl, function(gear) {
gear = JSON.parse(utils.string(gear));
gear.url = gearUrl;
//console.log('LoadGear', gearUrl);
//console.log(gear);
contentLoaded.gear[gear.reference_id] = gear;
assetLoadCount++;
checkContentLoaded();
}, onProgressCallback, onErrorCallback);
})(gearIndex);
}
// Load Bones / Animations
if (loadSkeleton && contentLoaded.skeleton == undefined) {
contentLoaded.skeleton = null;
loadPart(contentpath+'/animations/destiny_player_skeleton.js', function(skeleton) {
skeleton = JSON.parse(skeleton);
contentLoaded.skeleton = skeleton;
assetLoadCount++;
checkContentLoaded();
}, onProgressCallback, onErrorCallback);
if (loadAnimation) {
loadPart(contentpath+'/animations/'+animationPath, function(animations) {
animations = JSON.parse(animations);
contentLoaded.animations = animations;
assetLoadCount++;
checkContentLoaded();
}, onProgressCallback, onErrorCallback);
}
}
}
function loadAssetManifestContent(content) {
// Filter Regions
var filteredRegionIndexSets = [];
if (content.dye_index_set) {
//console.log('DyeIndexSet', content.dye_index_set);
filteredRegionIndexSets.push(content.dye_index_set);
}
if (content.region_index_sets) { // Use gender neutral sets
for (var setIndex in content.region_index_sets) {
var regionIndexSet = content.region_index_sets[setIndex];
//console.log('RegionIndexSet', setIndex, regionIndexSet);
var skipSet = false;
// regionKeysToNotLoad
//switch(parseInt(setIndex)) {
// case 2: // hud
// //case 4:
// case 3:
// case 6: // ammo
// case 21: // reticle
// skipSet = true;
// break;
// default:
// console.warn('RegionSetIndex', setIndex);
// break;
//}
if (skipSet) continue;
for (var j=0; j<regionIndexSet.length; j++) {
filteredRegionIndexSets.push(regionIndexSet[j]);
}
}
} else if (content.female_index_set && content.male_index_set) { // Use gender-specific set (ie armor)
//console.log('GenderedIndexSet', content.female_index_set, content.male_index_set);
filteredRegionIndexSets.push(isFemale ? content.female_index_set : content.male_index_set);
} else {
// This is probably a shader
//console.warn('NoIndexSetFound['+i+']', content);
}
// Build Asset Index Table
var geometryIndexes = {};
var textureIndexes = {};
var platedTextureIndexes = {};
for (var filteredRegionIndex in filteredRegionIndexSets) {
var filteredRegionIndexSet = filteredRegionIndexSets[filteredRegionIndex];
var index, i;
if (filteredRegionIndexSet == undefined) {
console.warn('MissingFilterRegionIndexSet', filteredRegionIndex, filteredRegionIndexSets);
continue;
}
// Shaders don't have geometry
if (filteredRegionIndexSet.geometry) {
for (i=0; i<filteredRegionIndexSet.geometry.length; i++) {
index = filteredRegionIndexSet.geometry[i];
geometryIndexes[index] = index;
}
}
for (i=0; i<filteredRegionIndexSet.textures.length; i++) {
index = filteredRegionIndexSet.textures[i];
textureIndexes[index] = index;
}
// Web only
if (filteredRegionIndexSet.plate_regions) {
for (i=0; i<filteredRegionIndexSet.plate_regions.length; i++) {
index = filteredRegionIndexSet.plate_regions[i];
platedTextureIndexes[index] = index;
}
}
// Apparently there are shaders?
if (filteredRegionIndexSet.shaders) {
console.warn('AssetHasShaders['+i+']', filteredRegionIndexSet.shaders);
}
}
// Tally up geometries and textures for loading
assetLoadTotal += Object.keys(geometryIndexes).length;
if (loadTextures) {
assetLoadTotal += Object.keys(textureIndexes).length;
assetLoadTotal += Object.keys(platedTextureIndexes).length;
assetLoadTotal++; // Envmap
}
// Remember everything for later
var contentRegions = {
//indexSets: filteredRegionIndexSets,
geometry: {},
textures: {},
platedTextures: {},
shaders: {}
};
// Load Geometry
for (var geometryIndex in geometryIndexes) {
(function(geometryIndex) {
loadGeometry(content.geometry[geometryIndex], function(geometry) {
//console.log('Geometry', geometry);
contentLoaded.geometry[geometry.fileIdentifier] = geometry;
contentRegions.geometry[geometryIndex] = geometry.fileIdentifier;
assetLoadCount++;
checkContentLoaded();
});
})(geometryIndex);
}
if (loadTextures) {
// EnvMap
var canvas = document.createElement('canvas');
canvas.width = 64;
canvas.height = 64;
var ctx = canvas.getContext('2d');
ctx.fillStyle = '#000000';
ctx.fillRect(0, 0, canvas.width, canvas.height);
var envMap = canvas.toDataURL('image/png');
loadDataTexture(envMap, DEFAULT_CUBEMAP, function(textureData) {
assetLoadCount++;
checkContentLoaded();
});
// Load Textures
for (var textureIndex in textureIndexes) {
(function(textureIndex) {
var texture = content.textures[textureIndex];
loadTexture(texture, false, function(textureData) {
contentRegions.textures[textureIndex] = textureData.referenceId;
assetLoadCount++;
checkContentLoaded();
});
})(textureIndex);
}
// Load Plated Textures
for (var platedTextureIndex in platedTextureIndexes) {
(function(platedTextureIndex) {
var platedTexture = content.plate_regions[platedTextureIndex];
loadTexture(platedTexture, true, function(textureData) {
contentRegions.platedTextures[platedTextureIndex] = textureData.referenceId;
assetLoadCount++;
checkContentLoaded();
});
})(platedTextureIndex);
}
}
return contentRegions;
}
// Check for when all content has loaded
function checkContentLoaded() {
if (assetLoadCount < assetLoadTotal) return;
if (contentParsed) return;
contentParsed = true;
parseContent(contentLoaded);
}
function loadPart(url, onLoad) {
var loader = new THREE.BungieNetLoader( this.manager );
loader.load(url+(noCache ? '?'+new Date().getTime() : ''), null, function (response) {
if (response instanceof ArrayBuffer) response = new Uint8Array(response);
if (onLoad) onLoad(response);
}, onProgressCallback, onErrorCallback);
}
function loadGeometry(geometry, onLoad) {
var url = contentpath+'/geometry/platform/'+platform+'/geometry/'+geometry;
loadTGXBin(url, onLoad, onProgressCallback, onErrorCallback);
}
// Spasm.TGXBinLoader
function loadTGXBin(url, onLoad) {
loadPart(url, function(data) {
//console.log(data);
var magic = utils.string(data, 0x0, 0x4); // TGXM
var version = utils.uint(data, 0x4);
var fileOffset = utils.uint(data, 0x8);
var fileCount = utils.uint(data, 0xC);
var fileIdentifier = utils.string(data, 0x10, 0x100);
//console.log(magic, version, fileOffset.toString(16), fileCount, fileIdentifier);
if (magic != 'TGXM') {
console.error('Invalid TGX File', url);
return;
}
var files = [];
var fileLookup = [];
var renderMetadata = false;
for (var f=0; f<fileCount; f++) {
var headerOffset = fileOffset+0x110*f;
var name = utils.string(data, headerOffset, 0x100);
var offset = utils.uint(data, headerOffset+0x100);
var type = utils.uint(data, headerOffset+0x104);
var size = utils.uint(data, headerOffset+0x108);
var fileData = data.slice(offset, offset+size);
//console.log('file['+f+']', headerOffset.toString(16), name, offset.toString(16), size);
if (name.indexOf('.js') != -1) { // render_metadata.js
fileData = JSON.parse(utils.string(fileData));
renderMetadata = fileData;
}
files.push({
name: name,
offset: offset,
type: type,
size: size,
data: fileData
});
fileLookup.push(name);
}
var tgxBin = {
url: url,
fileIdentifier: fileIdentifier,
files: files,
lookup: fileLookup,
metadata: renderMetadata
};
//console.log('LoadTGXBin', url);
//console.log(tgxBin);
contentLoaded.tgxms[url.indexOf('.bin') != -1 ? 'textures' : 'geometry'][url.slice(url.lastIndexOf('/')+1).split('.')[0]] = tgxBin;
if (onLoad) onLoad(tgxBin);
}, onProgressCallback, onErrorCallback);
}
function loadDataTexture(textureUri, referenceId, onLoad, isPlated) {
if (isPlated === undefined) isPlated = false;
var contentId = isPlated ? 'platedTextures' : 'textures';
if (contentLoaded[contentId][referenceId] != undefined) {
console.warn('CachedDataTexture['+referenceId+']', textureUri);
if (onLoad) onLoad(contentLoaded[contentId][referenceId]);
return;
}
var loader = new THREE.TextureLoader(this.manager);
var textureData = loader.load(textureUri, function(texture) {
if (onLoad) onLoad(texture);
}, onProgressCallback, onErrorCallback);
textureData.flipY = false;
textureData.minFilter = THREE.LinearMipMapLinearFilter;
//textureData.magFilter = THREE.NearestFilter;
textureData.wrapS = THREE.RepeatWrapping;
textureData.wrapT = THREE.RepeatWrapping;
textureData.name = referenceId;
textureData.src = textureUri;
contentLoaded[contentId][referenceId] = {
referenceId: referenceId,
texture: textureData
};
}
function loadTexture(texture, isPlated, onLoad) {
if (isPlated === undefined) isPlated = false;
var url = contentpath+'/geometry/platform/'+platform+'/'+(isPlated ? 'plated_textures' : 'textures')+'/'+texture;
var referenceId = texture.split('.')[0];
if (texture.indexOf('.bin') != -1) { // Mobile texture
loadTGXBin(url, function(tgxBin) {
//console.log('MobileTexture', tgxBin);
contentLoaded.mobileTextures[referenceId] = {
url: url,
referenceId: referenceId,
fileIdentifier: tgxBin.fileIdentifier,
texture: tgxBin.lookup
};
var count = 0;
var total = tgxBin.files.length;
for (var i=0; i<tgxBin.files.length; i++) {
(function(fileIndex) {
var textureFile = tgxBin.files[fileIndex];
if (contentLoaded['textures'][textureFile.name] !== undefined) {
//console.warn('CachedTexture', textureFile);
count++;
if (count == total && onLoad) onLoad(contentLoaded.mobileTextures[referenceId]);
return;
}
var textureData = loadMobileTexture(textureFile, function() {
count++;
//console.log('MobileTexture['+referenceId+']', textureFile.name, textureData.image.src);
if (count == total && onLoad) onLoad(contentLoaded.mobileTextures[referenceId]);
});
textureData.name = textureFile.name;
textureData.flipY = false;
textureData.minFilter = THREE.LinearFilter;
textureData.magFilter = THREE.LinearFilter;
textureData.wrapS = THREE.RepeatWrapping;
textureData.wrapT = THREE.RepeatWrapping;
contentLoaded['textures'][textureFile.name] = {
url: url,
mobileReferenceId: referenceId,
referenceId: textureFile.name,
texture: textureData
};
})(i);
}
});
} else {
var contentId = isPlated ? 'platedTextures' : 'textures';
if (contentLoaded[contentId][referenceId] !== undefined) {
//console.warn('CachedTexture', contentId+'_'+referenceId);
if (onLoad) onLoad(contentLoaded[contentId][referenceId]);
return;
}
var loader = new THREE.TextureLoader(this.manager);
var textureData = loader.load(url, function(texture) {
//console.log('Texture['+referenceId+']', textureData.image.src);
if (onLoad) onLoad(texture);
}, onProgressCallback, onErrorCallback);
textureData.name = referenceId;
textureData.flipY = false;
textureData.minFilter = THREE.LinearFilter;
textureData.magFilter = THREE.LinearFilter;
textureData.wrapS = THREE.RepeatWrapping;
textureData.wrapT = THREE.RepeatWrapping;
contentLoaded[contentId][referenceId] = {
url: url,
referenceId: referenceId,
texture: textureData
};
}
}
function loadMobileTexture(textureFile, onLoad) {
var isPng = utils.string(textureFile.data, 1, 3) == 'PNG';
var mimeType = 'image/'+(isPng ? 'png' : 'jpeg');
var urlCreator = window.URL || window.webkitURL;
var imageUrl = urlCreator.createObjectURL(new Blob([textureFile.data], {type: mimeType}));
var texture = new THREE.Texture();
var image = new Image();
image.onload = function () {
texture.image = image;
texture.needsUpdate = true;
if (onLoad) onLoad(texture);
};
image.src = imageUrl;
return texture;
}
function parseContent() {
console.log('ContentLoaded', contentLoaded);
// Set up THREE.Geometry and load skeleton (if any)
geometry = new THREE.Geometry();
geometry.bones = parseSkeleton();
hasBones = geometry.bones.length > 0;
var animation = hasBones && loadAnimation ? parseAnimation(geometry.bones) : false;
// Set up default white material
defaultMaterial = new THREE.MeshLambertMaterial({
emissive: 0x444444,
color: 0x777777,
//shading: THREE.FlatShading,
flatShading: true,
side: THREE.DoubleSide,
skinning: hasBones
});
defaultMaterial.name = 'DefaultMaterial';
materials = [];
if (!loadTextures) materials.push(defaultMaterial);
vertexOffset = 0;
for (var i=0; i<contentLoaded.items.length; i++) {
parseItem(contentLoaded.items[i]);
}
//for (var gearId in contentLoaded.gear) {
// var gear = contentLoaded.gear[gearId];
// parseGear(gear);
//}
if (typeof onLoadCallback !== 'function') {
console.warn('NoOnLoadCallback', geometry, materials, animation);
return;
}
onLoadCallback(geometry, materials, animation ? [animation] : []);
}
function parseItem(item) {
var gear = contentLoaded.gear[item.requestedId];
var shaderGear = item.shaderHash ? contentLoaded.gear[item.shaderHash] : null;
// TODO: Should iterate this, but its never has more than one
var regionIndexSets = item.gearAsset.content[0].region_index_sets;
var assetIndexSet = contentLoaded.regions[item.requestedId];
console.log('ParseItem', item, assetIndexSet);
// Figure out which geometry should be loaded ie class, gender
//var geometryHashes = [], geometryTextures = {};
var artContent = gear.art_content;
var artContentSets = gear.art_content_sets;
if (artContentSets && artContentSets.length > 1) {
//console.log('Requires Arrangement', artContentSets);
for (var r=0; r<artContentSets.length; r++) {
var artContentSet = artContentSets[r];
if (artContentSet.classHash == classHash) {
artContent = artContentSet.arrangement;
break;
}
}
} else if (artContentSets && artContentSets.length > 0) {
artContent = artContentSets[0].arrangement;
}