-
Notifications
You must be signed in to change notification settings - Fork 0
/
LoaderSupport.js
1711 lines (1306 loc) · 51.4 KB
/
LoaderSupport.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
/**
* @author Kai Salmen / https://kaisalmen.de
* Development repository: https://github.com/kaisalmen/WWOBJLoader
*/
'use strict';
if ( THREE.LoaderSupport === undefined ) { THREE.LoaderSupport = {} }
/**
* Validation functions.
* @class
*/
THREE.LoaderSupport.Validator = {
/**
* If given input is null or undefined, false is returned otherwise true.
*
* @param input Can be anything
* @returns {boolean}
*/
isValid: function( input ) {
return ( input !== null && input !== undefined );
},
/**
* If given input is null or undefined, the defaultValue is returned otherwise the given input.
*
* @param input Can be anything
* @param defaultValue Can be anything
* @returns {*}
*/
verifyInput: function( input, defaultValue ) {
return ( input === null || input === undefined ) ? defaultValue : input;
}
};
/**
* Callbacks utilized by loaders and builders.
* @class
*/
THREE.LoaderSupport.Callbacks = function () {
this.onProgress = null;
this.onReportError = null;
this.onMeshAlter = null;
this.onLoad = null;
this.onLoadMaterials = null;
};
THREE.LoaderSupport.Callbacks.prototype = {
constructor: THREE.LoaderSupport.Callbacks,
/**
* Register callback function that is invoked by internal function "announceProgress" to print feedback.
*
* @param {callback} callbackOnProgress Callback function for described functionality
*/
setCallbackOnProgress: function ( callbackOnProgress ) {
this.onProgress = THREE.LoaderSupport.Validator.verifyInput( callbackOnProgress, this.onProgress );
},
/**
* Register callback function that is invoked when an error is reported.
*
* @param {callback} callbackOnReportError Callback function for described functionality
*/
setCallbackOnReportError: function ( callbackOnReportError ) {
this.onReportError = THREE.LoaderSupport.Validator.verifyInput( callbackOnReportError, this.onReportError );
},
/**
* Register callback function that is called every time a mesh was loaded.
* Use {@link THREE.LoaderSupport.LoadedMeshUserOverride} for alteration instructions (geometry, material or disregard mesh).
*
* @param {callback} callbackOnMeshAlter Callback function for described functionality
*/
setCallbackOnMeshAlter: function ( callbackOnMeshAlter ) {
this.onMeshAlter = THREE.LoaderSupport.Validator.verifyInput( callbackOnMeshAlter, this.onMeshAlter );
},
/**
* Register callback function that is called once loading of the complete OBJ file is completed.
*
* @param {callback} callbackOnLoad Callback function for described functionality
*/
setCallbackOnLoad: function ( callbackOnLoad ) {
this.onLoad = THREE.LoaderSupport.Validator.verifyInput( callbackOnLoad, this.onLoad );
},
/**
* Register callback function that is called when materials have been loaded.
*
* @param {callback} callbackOnLoadMaterials Callback function for described functionality
*/
setCallbackOnLoadMaterials: function ( callbackOnLoadMaterials ) {
this.onLoadMaterials = THREE.LoaderSupport.Validator.verifyInput( callbackOnLoadMaterials, this.onLoadMaterials );
}
};
/**
* Object to return by callback onMeshAlter. Used to disregard a certain mesh or to return one to many meshes.
* @class
*
* @param {boolean} disregardMesh=false Tell implementation to completely disregard this mesh
* @param {boolean} disregardMesh=false Tell implementation that mesh(es) have been altered or added
*/
THREE.LoaderSupport.LoadedMeshUserOverride = function( disregardMesh, alteredMesh ) {
this.disregardMesh = disregardMesh === true;
this.alteredMesh = alteredMesh === true;
this.meshes = [];
};
THREE.LoaderSupport.LoadedMeshUserOverride.prototype = {
constructor: THREE.LoaderSupport.LoadedMeshUserOverride,
/**
* Add a mesh created within callback.
*
* @param {THREE.Mesh} mesh
*/
addMesh: function ( mesh ) {
this.meshes.push( mesh );
this.alteredMesh = true;
},
/**
* Answers if mesh shall be disregarded completely.
*
* @returns {boolean}
*/
isDisregardMesh: function () {
return this.disregardMesh;
},
/**
* Answers if new mesh(es) were created.
*
* @returns {boolean}
*/
providesAlteredMeshes: function () {
return this.alteredMesh;
}
};
/**
* A resource description used by {@link THREE.LoaderSupport.PrepData} and others.
* @class
*
* @param {string} url URL to the file
* @param {string} extension The file extension (type)
*/
THREE.LoaderSupport.ResourceDescriptor = function ( url, extension ) {
var urlParts = url.split( '/' );
this.path;
this.resourcePath;
this.name = url;
this.url = url;
if ( urlParts.length >= 2 ) {
this.path = THREE.LoaderSupport.Validator.verifyInput( urlParts.slice( 0, urlParts.length - 1).join( '/' ) + '/', this.path );
this.name = urlParts[ urlParts.length - 1 ];
this.url = url;
}
this.name = THREE.LoaderSupport.Validator.verifyInput( this.name, 'Unnamed_Resource' );
this.extension = THREE.LoaderSupport.Validator.verifyInput( extension, 'default' );
this.extension = this.extension.trim();
this.content = null;
};
THREE.LoaderSupport.ResourceDescriptor.prototype = {
constructor: THREE.LoaderSupport.ResourceDescriptor,
/**
* Set the content of this resource
*
* @param {Object} content The file content as arraybuffer or text
*/
setContent: function ( content ) {
this.content = THREE.LoaderSupport.Validator.verifyInput( content, null );
},
/**
* Allows to specify resourcePath for dependencies of specified resource.
* @param {string} resourcePath
*/
setResourcePath: function ( resourcePath ) {
this.resourcePath = THREE.LoaderSupport.Validator.verifyInput( resourcePath, this.resourcePath );
}
};
/**
* Configuration instructions to be used by run method.
* @class
*/
THREE.LoaderSupport.PrepData = function ( modelName ) {
this.logging = {
enabled: true,
debug: false
};
this.modelName = THREE.LoaderSupport.Validator.verifyInput( modelName, '' );
this.resources = [];
this.callbacks = new THREE.LoaderSupport.Callbacks();
};
THREE.LoaderSupport.PrepData.prototype = {
constructor: THREE.LoaderSupport.PrepData,
/**
* Enable or disable logging in general (except warn and error), plus enable or disable debug logging.
*
* @param {boolean} enabled True or false.
* @param {boolean} debug True or false.
*/
setLogging: function ( enabled, debug ) {
this.logging.enabled = enabled === true;
this.logging.debug = debug === true;
},
/**
* Returns all callbacks as {@link THREE.LoaderSupport.Callbacks}
*
* @returns {THREE.LoaderSupport.Callbacks}
*/
getCallbacks: function () {
return this.callbacks;
},
/**
* Add a resource description.
*
* @param {THREE.LoaderSupport.ResourceDescriptor} Adds a {@link THREE.LoaderSupport.ResourceDescriptor}
*/
addResource: function ( resource ) {
this.resources.push( resource );
},
/**
* Clones this object and returns it afterwards. Callbacks and resources are not cloned deep (references!).
*
* @returns {@link THREE.LoaderSupport.PrepData}
*/
clone: function () {
var clone = new THREE.LoaderSupport.PrepData( this.modelName );
clone.logging.enabled = this.logging.enabled;
clone.logging.debug = this.logging.debug;
clone.resources = this.resources;
clone.callbacks = this.callbacks;
var property, value;
for ( property in this ) {
value = this[ property ];
if ( ! clone.hasOwnProperty( property ) && typeof this[ property ] !== 'function' ) {
clone[ property ] = value;
}
}
return clone;
},
/**
* Identify files or content of interest from an Array of {@link THREE.LoaderSupport.ResourceDescriptor}.
*
* @param {THREE.LoaderSupport.ResourceDescriptor[]} resources Array of {@link THREE.LoaderSupport.ResourceDescriptor}
* @param Object fileDesc Object describing which resources are of interest (ext, type (string or UInt8Array) and ignore (boolean))
* @returns {{}} Object with each "ext" and the corresponding {@link THREE.LoaderSupport.ResourceDescriptor}
*/
checkResourceDescriptorFiles: function ( resources, fileDesc ) {
var resource, triple, i, found;
var result = {};
for ( var index in resources ) {
resource = resources[ index ];
found = false;
if ( ! THREE.LoaderSupport.Validator.isValid( resource.name ) ) continue;
if ( THREE.LoaderSupport.Validator.isValid( resource.content ) ) {
for ( i = 0; i < fileDesc.length && !found; i++ ) {
triple = fileDesc[ i ];
if ( resource.extension.toLowerCase() === triple.ext.toLowerCase() ) {
if ( triple.ignore ) {
found = true;
} else if ( triple.type === "ArrayBuffer" ) {
// fast-fail on bad type
if ( ! ( resource.content instanceof ArrayBuffer || resource.content instanceof Uint8Array ) ) throw 'Provided content is not of type ArrayBuffer! Aborting...';
result[ triple.ext ] = resource;
found = true;
} else if ( triple.type === "String" ) {
if ( ! ( typeof( resource.content ) === 'string' || resource.content instanceof String) ) throw 'Provided content is not of type String! Aborting...';
result[ triple.ext ] = resource;
found = true;
}
}
}
if ( !found ) throw 'Unidentified resource "' + resource.name + '": ' + resource.url;
} else {
// fast-fail on bad type
if ( ! ( typeof( resource.name ) === 'string' || resource.name instanceof String ) ) throw 'Provided file is not properly defined! Aborting...';
for ( i = 0; i < fileDesc.length && !found; i++ ) {
triple = fileDesc[ i ];
if ( resource.extension.toLowerCase() === triple.ext.toLowerCase() ) {
if ( ! triple.ignore ) result[ triple.ext ] = resource;
found = true;
}
}
if ( !found ) throw 'Unidentified resource "' + resource.name + '": ' + resource.url;
}
}
return result;
}
};
/**
* Builds one or many THREE.Mesh from one raw set of Arraybuffers, materialGroup descriptions and further parameters.
* Supports vertex, vertexColor, normal, uv and index buffers.
* @class
*/
THREE.LoaderSupport.MeshBuilder = function() {
this.validator = THREE.LoaderSupport.Validator;
this.logging = {
enabled: true,
debug: false
};
this.callbacks = new THREE.LoaderSupport.Callbacks();
this.materials = {};
};
THREE.LoaderSupport.MeshBuilder.LOADER_MESH_BUILDER_VERSION = '1.3.1';
console.info( 'Using THREE.LoaderSupport.MeshBuilder version: ' + THREE.LoaderSupport.MeshBuilder.LOADER_MESH_BUILDER_VERSION );
THREE.LoaderSupport.MeshBuilder.prototype = {
constructor: THREE.LoaderSupport.MeshBuilder,
/**
* Enable or disable logging in general (except warn and error), plus enable or disable debug logging.
*
* @param {boolean} enabled True or false.
* @param {boolean} debug True or false.
*/
setLogging: function ( enabled, debug ) {
this.logging.enabled = enabled === true;
this.logging.debug = debug === true;
},
/**
* Initializes the MeshBuilder (currently only default material initialisation).
*
*/
init: function () {
var defaultMaterial = new THREE.MeshStandardMaterial( { color: 0xDCF1FF } );
defaultMaterial.name = 'defaultMaterial';
var defaultVertexColorMaterial = new THREE.MeshStandardMaterial( { color: 0xDCF1FF } );
defaultVertexColorMaterial.name = 'defaultVertexColorMaterial';
defaultVertexColorMaterial.vertexColors = THREE.VertexColors;
var defaultLineMaterial = new THREE.LineBasicMaterial();
defaultLineMaterial.name = 'defaultLineMaterial';
var defaultPointMaterial = new THREE.PointsMaterial( { size: 1 } );
defaultPointMaterial.name = 'defaultPointMaterial';
var runtimeMaterials = {};
runtimeMaterials[ defaultMaterial.name ] = defaultMaterial;
runtimeMaterials[ defaultVertexColorMaterial.name ] = defaultVertexColorMaterial;
runtimeMaterials[ defaultLineMaterial.name ] = defaultLineMaterial;
runtimeMaterials[ defaultPointMaterial.name ] = defaultPointMaterial;
this.updateMaterials(
{
cmd: 'materialData',
materials: {
materialCloneInstructions: null,
serializedMaterials: null,
runtimeMaterials: runtimeMaterials
}
}
);
},
/**
* Set materials loaded by any supplier of an Array of {@link THREE.Material}.
*
* @param {THREE.Material[]} materials Array of {@link THREE.Material}
*/
setMaterials: function ( materials ) {
var payload = {
cmd: 'materialData',
materials: {
materialCloneInstructions: null,
serializedMaterials: null,
runtimeMaterials: this.validator.isValid( this.callbacks.onLoadMaterials ) ? this.callbacks.onLoadMaterials( materials ) : materials
}
};
this.updateMaterials( payload );
},
_setCallbacks: function ( callbacks ) {
if ( this.validator.isValid( callbacks.onProgress ) ) this.callbacks.setCallbackOnProgress( callbacks.onProgress );
if ( this.validator.isValid( callbacks.onReportError ) ) this.callbacks.setCallbackOnReportError( callbacks.onReportError );
if ( this.validator.isValid( callbacks.onMeshAlter ) ) this.callbacks.setCallbackOnMeshAlter( callbacks.onMeshAlter );
if ( this.validator.isValid( callbacks.onLoad ) ) this.callbacks.setCallbackOnLoad( callbacks.onLoad );
if ( this.validator.isValid( callbacks.onLoadMaterials ) ) this.callbacks.setCallbackOnLoadMaterials( callbacks.onLoadMaterials );
},
/**
* Delegates processing of the payload (mesh building or material update) to the corresponding functions (BW-compatibility).
*
* @param {Object} payload Raw Mesh or Material descriptions.
* @returns {THREE.Mesh[]} mesh Array of {@link THREE.Mesh} or null in case of material update
*/
processPayload: function ( payload ) {
if ( payload.cmd === 'meshData' ) {
return this.buildMeshes( payload );
} else if ( payload.cmd === 'materialData' ) {
this.updateMaterials( payload );
return null;
}
},
/**
* Builds one or multiple meshes from the data described in the payload (buffers, params, material info).
*
* @param {Object} meshPayload Raw mesh description (buffers, params, materials) used to build one to many meshes.
* @returns {THREE.Mesh[]} mesh Array of {@link THREE.Mesh}
*/
buildMeshes: function ( meshPayload ) {
var meshName = meshPayload.params.meshName;
var bufferGeometry = new THREE.BufferGeometry();
bufferGeometry.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( meshPayload.buffers.vertices ), 3 ) );
if ( this.validator.isValid( meshPayload.buffers.indices ) ) {
bufferGeometry.setIndex( new THREE.BufferAttribute( new Uint32Array( meshPayload.buffers.indices ), 1 ));
}
var haveVertexColors = this.validator.isValid( meshPayload.buffers.colors );
if ( haveVertexColors ) {
bufferGeometry.addAttribute( 'color', new THREE.BufferAttribute( new Float32Array( meshPayload.buffers.colors ), 3 ) );
}
if ( this.validator.isValid( meshPayload.buffers.normals ) ) {
bufferGeometry.addAttribute( 'normal', new THREE.BufferAttribute( new Float32Array( meshPayload.buffers.normals ), 3 ) );
} else {
bufferGeometry.computeVertexNormals();
}
if ( this.validator.isValid( meshPayload.buffers.uvs ) ) {
bufferGeometry.addAttribute( 'uv', new THREE.BufferAttribute( new Float32Array( meshPayload.buffers.uvs ), 2 ) );
}
var material, materialName, key;
var materialNames = meshPayload.materials.materialNames;
var createMultiMaterial = meshPayload.materials.multiMaterial;
var multiMaterials = [];
for ( key in materialNames ) {
materialName = materialNames[ key ];
material = this.materials[ materialName ];
if ( createMultiMaterial ) multiMaterials.push( material );
}
if ( createMultiMaterial ) {
material = multiMaterials;
var materialGroups = meshPayload.materials.materialGroups;
var materialGroup;
for ( key in materialGroups ) {
materialGroup = materialGroups[ key ];
bufferGeometry.addGroup( materialGroup.start, materialGroup.count, materialGroup.index );
}
}
var meshes = [];
var mesh;
var callbackOnMeshAlter = this.callbacks.onMeshAlter;
var callbackOnMeshAlterResult;
var useOrgMesh = true;
var geometryType = this.validator.verifyInput( meshPayload.geometryType, 0 );
if ( this.validator.isValid( callbackOnMeshAlter ) ) {
callbackOnMeshAlterResult = callbackOnMeshAlter(
{
detail: {
meshName: meshName,
bufferGeometry: bufferGeometry,
material: material,
geometryType: geometryType
}
}
);
if ( this.validator.isValid( callbackOnMeshAlterResult ) ) {
if ( callbackOnMeshAlterResult.isDisregardMesh() ) {
useOrgMesh = false;
} else if ( callbackOnMeshAlterResult.providesAlteredMeshes() ) {
for ( var i in callbackOnMeshAlterResult.meshes ) {
meshes.push( callbackOnMeshAlterResult.meshes[ i ] );
}
useOrgMesh = false;
}
}
}
if ( useOrgMesh ) {
if ( meshPayload.computeBoundingSphere ) bufferGeometry.computeBoundingSphere();
if ( geometryType === 0 ) {
mesh = new THREE.Mesh( bufferGeometry, material );
} else if ( geometryType === 1) {
mesh = new THREE.LineSegments( bufferGeometry, material );
} else {
mesh = new THREE.Points( bufferGeometry, material );
}
mesh.name = meshName;
meshes.push( mesh );
}
var progressMessage;
if ( this.validator.isValid( meshes ) && meshes.length > 0 ) {
var meshNames = [];
for ( var i in meshes ) {
mesh = meshes[ i ];
meshNames[ i ] = mesh.name;
}
progressMessage = 'Adding mesh(es) (' + meshNames.length + ': ' + meshNames + ') from input mesh: ' + meshName;
progressMessage += ' (' + ( meshPayload.progress.numericalValue * 100 ).toFixed( 2 ) + '%)';
} else {
progressMessage = 'Not adding mesh: ' + meshName;
progressMessage += ' (' + ( meshPayload.progress.numericalValue * 100 ).toFixed( 2 ) + '%)';
}
var callbackOnProgress = this.callbacks.onProgress;
if ( this.validator.isValid( callbackOnProgress ) ) {
var event = new CustomEvent( 'MeshBuilderEvent', {
detail: {
type: 'progress',
modelName: meshPayload.params.meshName,
text: progressMessage,
numericalValue: meshPayload.progress.numericalValue
}
} );
callbackOnProgress( event );
}
return meshes;
},
/**
* Updates the materials with contained material objects (sync) or from alteration instructions (async).
*
* @param {Object} materialPayload Material update instructions
*/
updateMaterials: function ( materialPayload ) {
var material, materialName;
var materialCloneInstructions = materialPayload.materials.materialCloneInstructions;
if ( this.validator.isValid( materialCloneInstructions ) ) {
var materialNameOrg = materialCloneInstructions.materialNameOrg;
var materialOrg = this.materials[ materialNameOrg ];
if ( this.validator.isValid( materialNameOrg ) ) {
material = materialOrg.clone();
materialName = materialCloneInstructions.materialName;
material.name = materialName;
var materialProperties = materialCloneInstructions.materialProperties;
for ( var key in materialProperties ) {
if ( material.hasOwnProperty( key ) && materialProperties.hasOwnProperty( key ) ) material[ key ] = materialProperties[ key ];
}
this.materials[ materialName ] = material;
} else {
console.warn( 'Requested material "' + materialNameOrg + '" is not available!' );
}
}
var materials = materialPayload.materials.serializedMaterials;
if ( this.validator.isValid( materials ) && Object.keys( materials ).length > 0 ) {
var loader = new THREE.MaterialLoader();
var materialJson;
for ( materialName in materials ) {
materialJson = materials[ materialName ];
if ( this.validator.isValid( materialJson ) ) {
material = loader.parse( materialJson );
if ( this.logging.enabled ) console.info( 'De-serialized material with name "' + materialName + '" will be added.' );
this.materials[ materialName ] = material;
}
}
}
materials = materialPayload.materials.runtimeMaterials;
if ( this.validator.isValid( materials ) && Object.keys( materials ).length > 0 ) {
for ( materialName in materials ) {
material = materials[ materialName ];
if ( this.logging.enabled ) console.info( 'Material with name "' + materialName + '" will be added.' );
this.materials[ materialName ] = material;
}
}
},
/**
* Returns the mapping object of material name and corresponding jsonified material.
*
* @returns {Object} Map of Materials in JSON representation
*/
getMaterialsJSON: function () {
var materialsJSON = {};
var material;
for ( var materialName in this.materials ) {
material = this.materials[ materialName ];
materialsJSON[ materialName ] = material.toJSON();
}
return materialsJSON;
},
/**
* Returns the mapping object of material name and corresponding material.
*
* @returns {Object} Map of {@link THREE.Material}
*/
getMaterials: function () {
return this.materials;
}
};
/**
* This class provides means to transform existing parser code into a web worker. It defines a simple communication protocol
* which allows to configure the worker and receive raw mesh data during execution.
* @class
*/
THREE.LoaderSupport.WorkerSupport = function () {
this.logging = {
enabled: true,
debug: false
};
//Choose implementation of worker based on environment
this.loaderWorker = typeof window !== "undefined" ? new THREE.LoaderSupport.WorkerSupport.LoaderWorker() : new THREE.LoaderSupport.WorkerSupport.NodeLoaderWorker();
};
THREE.LoaderSupport.WorkerSupport.WORKER_SUPPORT_VERSION = '2.3.0';
console.info( 'Using THREE.LoaderSupport.WorkerSupport version: ' + THREE.LoaderSupport.WorkerSupport.WORKER_SUPPORT_VERSION );
THREE.LoaderSupport.WorkerSupport.prototype = {
constructor: THREE.LoaderSupport.WorkerSupport,
/**
* Enable or disable logging in general (except warn and error), plus enable or disable debug logging.
*
* @param {boolean} enabled True or false.
* @param {boolean} debug True or false.
*/
setLogging: function ( enabled, debug ) {
this.logging.enabled = enabled === true;
this.logging.debug = debug === true;
this.loaderWorker.setLogging( this.logging.enabled, this.logging.debug );
},
/**
* Forces all ArrayBuffers to be transferred to worker to be copied.
*
* @param {boolean} forceWorkerDataCopy True or false.
*/
setForceWorkerDataCopy: function ( forceWorkerDataCopy ) {
this.loaderWorker.setForceCopy( forceWorkerDataCopy );
},
/**
* Validate the status of worker code and the derived worker.
*
* @param {Function} functionCodeBuilder Function that is invoked with funcBuildObject and funcBuildSingleton that allows stringification of objects and singletons.
* @param {String} parserName Name of the Parser object
* @param {String[]} libLocations URL of libraries that shall be added to worker code relative to libPath
* @param {String} libPath Base path used for loading libraries
* @param {THREE.LoaderSupport.WorkerRunnerRefImpl} runnerImpl The default worker parser wrapper implementation (communication and execution). An extended class could be passed here.
*/
validate: function ( functionCodeBuilder, parserName, libLocations, libPath, runnerImpl ) {
if ( THREE.LoaderSupport.Validator.isValid( this.loaderWorker.worker ) ) return;
if ( this.logging.enabled ) {
console.info( 'WorkerSupport: Building worker code...' );
console.time( 'buildWebWorkerCode' );
}
if ( THREE.LoaderSupport.Validator.isValid( runnerImpl ) ) {
if ( this.logging.enabled ) console.info( 'WorkerSupport: Using "' + runnerImpl.runnerName + '" as Runner class for worker.' );
// Browser implementation
} else if ( typeof window !== "undefined" ) {
runnerImpl = THREE.LoaderSupport.WorkerRunnerRefImpl;
if ( this.logging.enabled ) console.info( 'WorkerSupport: Using DEFAULT "THREE.LoaderSupport.WorkerRunnerRefImpl" as Runner class for worker.' );
// NodeJS implementation
} else {
runnerImpl = THREE.LoaderSupport.NodeWorkerRunnerRefImpl;
if ( this.logging.enabled ) console.info( 'WorkerSupport: Using DEFAULT "THREE.LoaderSupport.NodeWorkerRunnerRefImpl" as Runner class for worker.' );
}
var userWorkerCode = functionCodeBuilder( THREE.LoaderSupport.WorkerSupport.CodeSerializer );
userWorkerCode += 'var Parser = '+ parserName + ';\n\n';
userWorkerCode += THREE.LoaderSupport.WorkerSupport.CodeSerializer.serializeClass( runnerImpl.runnerName, runnerImpl );
userWorkerCode += 'new ' + runnerImpl.runnerName + '();\n\n';
var scope = this;
if ( THREE.LoaderSupport.Validator.isValid( libLocations ) && libLocations.length > 0 ) {
var libsContent = '';
var loadAllLibraries = function ( path, locations ) {
if ( locations.length === 0 ) {
scope.loaderWorker.initWorker( libsContent + userWorkerCode, runnerImpl.runnerName );
if ( scope.logging.enabled ) console.timeEnd( 'buildWebWorkerCode' );
} else {
var loadedLib = function ( contentAsString ) {
libsContent += contentAsString;
loadAllLibraries( path, locations );
};
var fileLoader = new THREE.FileLoader();
fileLoader.setPath( path );
fileLoader.setResponseType( 'text' );
fileLoader.load( locations[ 0 ], loadedLib );
locations.shift();
}
};
loadAllLibraries( libPath, libLocations );
} else {
this.loaderWorker.initWorker( userWorkerCode, runnerImpl.runnerName );
if ( this.logging.enabled ) console.timeEnd( 'buildWebWorkerCode' );
}
},
/**
* Specify functions that should be build when new raw mesh data becomes available and when the parser is finished.
*
* @param {Function} meshBuilder The mesh builder function. Default is {@link THREE.LoaderSupport.MeshBuilder}.
* @param {Function} onLoad The function that is called when parsing is complete.
*/
setCallbacks: function ( meshBuilder, onLoad ) {
this.loaderWorker.setCallbacks( meshBuilder, onLoad );
},
/**
* Runs the parser with the provided configuration.
*
* @param {Object} payload Raw mesh description (buffers, params, materials) used to build one to many meshes.
*/
run: function ( payload ) {
this.loaderWorker.run( payload );
},
/**
* Request termination of worker once parser is finished.
*
* @param {boolean} terminateRequested True or false.
*/
setTerminateRequested: function ( terminateRequested ) {
this.loaderWorker.setTerminateRequested( terminateRequested );
}
};
THREE.LoaderSupport.WorkerSupport.LoaderWorker = function () {
this._reset();
};
THREE.LoaderSupport.WorkerSupport.LoaderWorker.prototype = {
constructor: THREE.LoaderSupport.WorkerSupport.LoaderWorker,
_reset: function () {
this.logging = {
enabled: true,
debug: false
};
this.worker = null;
this.runnerImplName = null;
this.callbacks = {
meshBuilder: null,
onLoad: null
};
this.terminateRequested = false;
this.queuedMessage = null;
this.started = false;
this.forceCopy = false;
},
/**
* Check support for Workers and other necessary features returning
* reason if the environment is unsupported
*
* @returns {string|undefined} Returns undefined if supported, or
* string with error if not supported
*/
checkSupport: function() {
if ( window.Worker === undefined ) return "This browser does not support web workers!";
if ( window.Blob === undefined ) return "This browser does not support Blob!";
if ( typeof window.URL.createObjectURL !== 'function' ) return "This browser does not support Object creation from URL!";
},
setLogging: function ( enabled, debug ) {
this.logging.enabled = enabled === true;
this.logging.debug = debug === true;
},
setForceCopy: function ( forceCopy ) {
this.forceCopy = forceCopy === true;
},
initWorker: function ( code, runnerImplName ) {
var supportError = this.checkSupport();
if ( supportError ) {
throw supportError;
}
this.runnerImplName = runnerImplName;
var blob = new Blob( [ code ], { type: 'application/javascript' } );
this.worker = new Worker( window.URL.createObjectURL( blob ) );
this.worker.onmessage = this._receiveWorkerMessage;
// set referemce to this, then processing in worker scope within "_receiveWorkerMessage" can access members
this.worker.runtimeRef = this;
// process stored queuedMessage
this._postMessage();
},
/**
* Executed in worker scope
*/
_receiveWorkerMessage: function ( e ) {
var payload = e.data;
switch ( payload.cmd ) {
case 'meshData':
case 'materialData':
case 'imageData':
this.runtimeRef.callbacks.meshBuilder( payload );
break;
case 'complete':
this.runtimeRef.queuedMessage = null;
this.started = false;
this.runtimeRef.callbacks.onLoad( payload.msg );
if ( this.runtimeRef.terminateRequested ) {
if ( this.runtimeRef.logging.enabled ) console.info( 'WorkerSupport [' + this.runtimeRef.runnerImplName + ']: Run is complete. Terminating application on request!' );
this.runtimeRef._terminate();
}
break;
case 'error':
console.error( 'WorkerSupport [' + this.runtimeRef.runnerImplName + ']: Reported error: ' + payload.msg );
this.runtimeRef.queuedMessage = null;
this.started = false;
this.runtimeRef.callbacks.onLoad( payload.msg );
if ( this.runtimeRef.terminateRequested ) {
if ( this.runtimeRef.logging.enabled ) console.info( 'WorkerSupport [' + this.runtimeRef.runnerImplName + ']: Run reported error. Terminating application on request!' );
this.runtimeRef._terminate();
}
break;
default:
console.error( 'WorkerSupport [' + this.runtimeRef.runnerImplName + ']: Received unknown command: ' + payload.cmd );
break;
}
},
setCallbacks: function ( meshBuilder, onLoad ) {
this.callbacks.meshBuilder = THREE.LoaderSupport.Validator.verifyInput( meshBuilder, this.callbacks.meshBuilder );
this.callbacks.onLoad = THREE.LoaderSupport.Validator.verifyInput( onLoad, this.callbacks.onLoad );
},
run: function( payload ) {
if ( THREE.LoaderSupport.Validator.isValid( this.queuedMessage ) ) {
console.warn( 'Already processing message. Rejecting new run instruction' );
return;
} else {
this.queuedMessage = payload;
this.started = true;
}
if ( ! THREE.LoaderSupport.Validator.isValid( this.callbacks.meshBuilder ) ) throw 'Unable to run as no "MeshBuilder" callback is set.';
if ( ! THREE.LoaderSupport.Validator.isValid( this.callbacks.onLoad ) ) throw 'Unable to run as no "onLoad" callback is set.';
if ( payload.cmd !== 'run' ) payload.cmd = 'run';
if ( THREE.LoaderSupport.Validator.isValid( payload.logging ) ) {
payload.logging.enabled = payload.logging.enabled === true;
payload.logging.debug = payload.logging.debug === true;