-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
Copy pathMaterial.js
1564 lines (1439 loc) · 61 KB
/
Material.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
import Cartesian2 from '../Core/Cartesian2.js';
import clone from '../Core/clone.js';
import Color from '../Core/Color.js';
import combine from '../Core/combine.js';
import createGuid from '../Core/createGuid.js';
import defaultValue from '../Core/defaultValue.js';
import defined from '../Core/defined.js';
import defineProperties from '../Core/defineProperties.js';
import destroyObject from '../Core/destroyObject.js';
import DeveloperError from '../Core/DeveloperError.js';
import isArray from '../Core/isArray.js';
import loadCRN from '../Core/loadCRN.js';
import loadKTX from '../Core/loadKTX.js';
import Matrix2 from '../Core/Matrix2.js';
import Matrix3 from '../Core/Matrix3.js';
import Matrix4 from '../Core/Matrix4.js';
import Resource from '../Core/Resource.js';
import CubeMap from '../Renderer/CubeMap.js';
import Texture from '../Renderer/Texture.js';
import AspectRampMaterial from '../Shaders/Materials/AspectRampMaterial.js';
import BumpMapMaterial from '../Shaders/Materials/BumpMapMaterial.js';
import CheckerboardMaterial from '../Shaders/Materials/CheckerboardMaterial.js';
import DotMaterial from '../Shaders/Materials/DotMaterial.js';
import ElevationContourMaterial from '../Shaders/Materials/ElevationContourMaterial.js';
import ElevationRampMaterial from '../Shaders/Materials/ElevationRampMaterial.js';
import FadeMaterial from '../Shaders/Materials/FadeMaterial.js';
import GridMaterial from '../Shaders/Materials/GridMaterial.js';
import NormalMapMaterial from '../Shaders/Materials/NormalMapMaterial.js';
import PolylineArrowMaterial from '../Shaders/Materials/PolylineArrowMaterial.js';
import PolylineDashMaterial from '../Shaders/Materials/PolylineDashMaterial.js';
import PolylineGlowMaterial from '../Shaders/Materials/PolylineGlowMaterial.js';
import PolylineOutlineMaterial from '../Shaders/Materials/PolylineOutlineMaterial.js';
import RimLightingMaterial from '../Shaders/Materials/RimLightingMaterial.js';
import SlopeRampMaterial from '../Shaders/Materials/SlopeRampMaterial.js';
import StripeMaterial from '../Shaders/Materials/StripeMaterial.js';
import WaterMaterial from '../Shaders/Materials/Water.js';
import when from '../ThirdParty/when.js';
/**
* A Material defines surface appearance through a combination of diffuse, specular,
* normal, emission, and alpha components. These values are specified using a
* JSON schema called Fabric which gets parsed and assembled into glsl shader code
* behind-the-scenes. Check out the {@link https://github.com/AnalyticalGraphicsInc/cesium/wiki/Fabric|wiki page}
* for more details on Fabric.
* <br /><br />
* <style type="text/css">
* #materialDescriptions code {
* font-weight: normal;
* font-family: Consolas, 'Lucida Console', Monaco, monospace;
* color: #A35A00;
* }
* #materialDescriptions ul, #materialDescriptions ul ul {
* list-style-type: none;
* }
* #materialDescriptions ul ul {
* margin-bottom: 10px;
* }
* #materialDescriptions ul ul li {
* font-weight: normal;
* color: #000000;
* text-indent: -2em;
* margin-left: 2em;
* }
* #materialDescriptions ul li {
* font-weight: bold;
* color: #0053CF;
* }
* </style>
*
* Base material types and their uniforms:
* <div id='materialDescriptions'>
* <ul>
* <li>Color</li>
* <ul>
* <li><code>color</code>: rgba color object.</li>
* </ul>
* <li>Image</li>
* <ul>
* <li><code>image</code>: path to image.</li>
* <li><code>repeat</code>: Object with x and y values specifying the number of times to repeat the image.</li>
* </ul>
* <li>DiffuseMap</li>
* <ul>
* <li><code>image</code>: path to image.</li>
* <li><code>channels</code>: Three character string containing any combination of r, g, b, and a for selecting the desired image channels.</li>
* <li><code>repeat</code>: Object with x and y values specifying the number of times to repeat the image.</li>
* </ul>
* <li>AlphaMap</li>
* <ul>
* <li><code>image</code>: path to image.</li>
* <li><code>channel</code>: One character string containing r, g, b, or a for selecting the desired image channel. </li>
* <li><code>repeat</code>: Object with x and y values specifying the number of times to repeat the image.</li>
* </ul>
* <li>SpecularMap</li>
* <ul>
* <li><code>image</code>: path to image.</li>
* <li><code>channel</code>: One character string containing r, g, b, or a for selecting the desired image channel. </li>
* <li><code>repeat</code>: Object with x and y values specifying the number of times to repeat the image.</li>
* </ul>
* <li>EmissionMap</li>
* <ul>
* <li><code>image</code>: path to image.</li>
* <li><code>channels</code>: Three character string containing any combination of r, g, b, and a for selecting the desired image channels. </li>
* <li><code>repeat</code>: Object with x and y values specifying the number of times to repeat the image.</li>
* </ul>
* <li>BumpMap</li>
* <ul>
* <li><code>image</code>: path to image.</li>
* <li><code>channel</code>: One character string containing r, g, b, or a for selecting the desired image channel. </li>
* <li><code>repeat</code>: Object with x and y values specifying the number of times to repeat the image.</li>
* <li><code>strength</code>: Bump strength value between 0.0 and 1.0 where 0.0 is small bumps and 1.0 is large bumps.</li>
* </ul>
* <li>NormalMap</li>
* <ul>
* <li><code>image</code>: path to image.</li>
* <li><code>channels</code>: Three character string containing any combination of r, g, b, and a for selecting the desired image channels. </li>
* <li><code>repeat</code>: Object with x and y values specifying the number of times to repeat the image.</li>
* <li><code>strength</code>: Bump strength value between 0.0 and 1.0 where 0.0 is small bumps and 1.0 is large bumps.</li>
* </ul>
* <li>Grid</li>
* <ul>
* <li><code>color</code>: rgba color object for the whole material.</li>
* <li><code>cellAlpha</code>: Alpha value for the cells between grid lines. This will be combined with color.alpha.</li>
* <li><code>lineCount</code>: Object with x and y values specifying the number of columns and rows respectively.</li>
* <li><code>lineThickness</code>: Object with x and y values specifying the thickness of grid lines (in pixels where available).</li>
* <li><code>lineOffset</code>: Object with x and y values specifying the offset of grid lines (range is 0 to 1).</li>
* </ul>
* <li>Stripe</li>
* <ul>
* <li><code>horizontal</code>: Boolean that determines if the stripes are horizontal or vertical.</li>
* <li><code>evenColor</code>: rgba color object for the stripe's first color.</li>
* <li><code>oddColor</code>: rgba color object for the stripe's second color.</li>
* <li><code>offset</code>: Number that controls at which point into the pattern to begin drawing; with 0.0 being the beginning of the even color, 1.0 the beginning of the odd color, 2.0 being the even color again, and any multiple or fractional values being in between.</li>
* <li><code>repeat</code>: Number that controls the total number of stripes, half light and half dark.</li>
* </ul>
* <li>Checkerboard</li>
* <ul>
* <li><code>lightColor</code>: rgba color object for the checkerboard's light alternating color.</li>
* <li><code>darkColor</code>: rgba color object for the checkerboard's dark alternating color.</li>
* <li><code>repeat</code>: Object with x and y values specifying the number of columns and rows respectively.</li>
* </ul>
* <li>Dot</li>
* <ul>
* <li><code>lightColor</code>: rgba color object for the dot color.</li>
* <li><code>darkColor</code>: rgba color object for the background color.</li>
* <li><code>repeat</code>: Object with x and y values specifying the number of columns and rows of dots respectively.</li>
* </ul>
* <li>Water</li>
* <ul>
* <li><code>baseWaterColor</code>: rgba color object base color of the water.</li>
* <li><code>blendColor</code>: rgba color object used when blending from water to non-water areas.</li>
* <li><code>specularMap</code>: Single channel texture used to indicate areas of water.</li>
* <li><code>normalMap</code>: Normal map for water normal perturbation.</li>
* <li><code>frequency</code>: Number that controls the number of waves.</li>
* <li><code>normalMap</code>: Normal map for water normal perturbation.</li>
* <li><code>animationSpeed</code>: Number that controls the animations speed of the water.</li>
* <li><code>amplitude</code>: Number that controls the amplitude of water waves.</li>
* <li><code>specularIntensity</code>: Number that controls the intensity of specular reflections.</li>
* </ul>
* <li>RimLighting</li>
* <ul>
* <li><code>color</code>: diffuse color and alpha.</li>
* <li><code>rimColor</code>: diffuse color and alpha of the rim.</li>
* <li><code>width</code>: Number that determines the rim's width.</li>
* </ul>
* <li>Fade</li>
* <ul>
* <li><code>fadeInColor</code>: diffuse color and alpha at <code>time</code></li>
* <li><code>fadeOutColor</code>: diffuse color and alpha at <code>maximumDistance</code> from <code>time</code></li>
* <li><code>maximumDistance</code>: Number between 0.0 and 1.0 where the <code>fadeInColor</code> becomes the <code>fadeOutColor</code>. A value of 0.0 gives the entire material a color of <code>fadeOutColor</code> and a value of 1.0 gives the the entire material a color of <code>fadeInColor</code></li>
* <li><code>repeat</code>: true if the fade should wrap around the texture coodinates.</li>
* <li><code>fadeDirection</code>: Object with x and y values specifying if the fade should be in the x and y directions.</li>
* <li><code>time</code>: Object with x and y values between 0.0 and 1.0 of the <code>fadeInColor</code> position</li>
* </ul>
* <li>PolylineArrow</li>
* <ul>
* <li><code>color</code>: diffuse color and alpha.</li>
* </ul>
* <li>PolylineDash</li>
* <ul>
* <li><code>color</code>: color for the line.</li>
* <li><code>gapColor</code>: color for the gaps in the line.</li>
* <li><code>dashLength</code>: Dash length in pixels.</li>
* <li><code>dashPattern</code>: The 16 bit stipple pattern for the line..</li>
* </ul>
* <li>PolylineGlow</li>
* <ul>
* <li><code>color</code>: color and maximum alpha for the glow on the line.</li>
* <li><code>glowPower</code>: strength of the glow, as a percentage of the total line width (less than 1.0).</li>
* <li><code>taperPower</code>: strength of the tapering effect, as a percentage of the total line length. If 1.0 or higher, no taper effect is used.</li>
* </ul>
* <li>PolylineOutline</li>
* <ul>
* <li><code>color</code>: diffuse color and alpha for the interior of the line.</li>
* <li><code>outlineColor</code>: diffuse color and alpha for the outline.</li>
* <li><code>outlineWidth</code>: width of the outline in pixels.</li>
* </ul>
* <li>ElevationContour</li>
* <ul>
* <li><code>color</code>: color and alpha for the contour line.</li>
* <li><code>spacing</code>: spacing for contour lines in meters.</li>
* <li><code>width</code>: Number specifying the width of the grid lines in pixels.</li>
* </ul>
* <li>ElevationRamp</li>
* <ul>
* <li><code>image</code>: color ramp image to use for coloring the terrain.</li>
* <li><code>minimumHeight</code>: minimum height for the ramp.</li>
* <li><code>maximumHeight</code>: maximum height for the ramp.</li>
* </ul>
* <li>SlopeRamp</li>
* <ul>
* <li><code>image</code>: color ramp image to use for coloring the terrain by slope.</li>
* </ul>
* <li>AspectRamp</li>
* <ul>
* <li><code>image</code>: color ramp image to use for color the terrain by aspect.</li>
* </ul>
* </ul>
* </ul>
* </div>
*
* @alias Material
*
* @param {Object} [options] Object with the following properties:
* @param {Boolean} [options.strict=false] Throws errors for issues that would normally be ignored, including unused uniforms or materials.
* @param {Boolean|Function} [options.translucent=true] When <code>true</code> or a function that returns <code>true</code>, the geometry
* with this material is expected to appear translucent.
* @param {Object} options.fabric The fabric JSON used to generate the material.
*
* @constructor
*
* @exception {DeveloperError} fabric: uniform has invalid type.
* @exception {DeveloperError} fabric: uniforms and materials cannot share the same property.
* @exception {DeveloperError} fabric: cannot have source and components in the same section.
* @exception {DeveloperError} fabric: property name is not valid. It should be 'type', 'materials', 'uniforms', 'components', or 'source'.
* @exception {DeveloperError} fabric: property name is not valid. It should be 'diffuse', 'specular', 'shininess', 'normal', 'emission', or 'alpha'.
* @exception {DeveloperError} strict: shader source does not use string.
* @exception {DeveloperError} strict: shader source does not use uniform.
* @exception {DeveloperError} strict: shader source does not use material.
*
* @see {@link https://github.com/AnalyticalGraphicsInc/cesium/wiki/Fabric|Fabric wiki page} for a more detailed options of Fabric.
*
* @demo {@link https://sandcastle.cesium.com/index.html?src=Materials.html|Cesium Sandcastle Materials Demo}
*
* @example
* // Create a color material with fromType:
* polygon.material = Cesium.Material.fromType('Color');
* polygon.material.uniforms.color = new Cesium.Color(1.0, 1.0, 0.0, 1.0);
*
* // Create the default material:
* polygon.material = new Cesium.Material();
*
* // Create a color material with full Fabric notation:
* polygon.material = new Cesium.Material({
* fabric : {
* type : 'Color',
* uniforms : {
* color : new Cesium.Color(1.0, 1.0, 0.0, 1.0)
* }
* }
* });
*/
function Material(options) {
/**
* The material type. Can be an existing type or a new type. If no type is specified in fabric, type is a GUID.
* @type {String}
* @default undefined
*/
this.type = undefined;
/**
* The glsl shader source for this material.
* @type {String}
* @default undefined
*/
this.shaderSource = undefined;
/**
* Maps sub-material names to Material objects.
* @type {Object}
* @default undefined
*/
this.materials = undefined;
/**
* Maps uniform names to their values.
* @type {Object}
* @default undefined
*/
this.uniforms = undefined;
this._uniforms = undefined;
/**
* When <code>true</code> or a function that returns <code>true</code>,
* the geometry is expected to appear translucent.
* @type {Boolean|Function}
* @default undefined
*/
this.translucent = undefined;
this._strict = undefined;
this._template = undefined;
this._count = undefined;
this._texturePaths = {};
this._loadedImages = [];
this._loadedCubeMaps = [];
this._textures = {};
this._updateFunctions = [];
this._defaultTexture = undefined;
initializeMaterial(options, this);
defineProperties(this, {
type : {
value : this.type,
writable : false
}
});
if (!defined(Material._uniformList[this.type])) {
Material._uniformList[this.type] = Object.keys(this._uniforms);
}
}
// Cached list of combined uniform names indexed by type.
// Used to get the list of uniforms in the same order.
Material._uniformList = {};
/**
* Creates a new material using an existing material type.
* <br /><br />
* Shorthand for: new Material({fabric : {type : type}});
*
* @param {String} type The base material type.
* @param {Object} [uniforms] Overrides for the default uniforms.
* @returns {Material} New material object.
*
* @exception {DeveloperError} material with that type does not exist.
*
* @example
* var material = Cesium.Material.fromType('Color', {
* color : new Cesium.Color(1.0, 0.0, 0.0, 1.0)
* });
*/
Material.fromType = function(type, uniforms) {
//>>includeStart('debug', pragmas.debug);
if (!defined(Material._materialCache.getMaterial(type))) {
throw new DeveloperError('material with type \'' + type + '\' does not exist.');
}
//>>includeEnd('debug');
var material = new Material({
fabric : {
type : type
}
});
if (defined(uniforms)) {
for (var name in uniforms) {
if (uniforms.hasOwnProperty(name)) {
material.uniforms[name] = uniforms[name];
}
}
}
return material;
};
/**
* Gets whether or not this material is translucent.
* @returns {Boolean} <code>true</code> if this material is translucent, <code>false</code> otherwise.
*/
Material.prototype.isTranslucent = function() {
if (defined(this.translucent)) {
if (typeof this.translucent === 'function') {
return this.translucent();
}
return this.translucent;
}
var translucent = true;
var funcs = this._translucentFunctions;
var length = funcs.length;
for (var i = 0; i < length; ++i) {
var func = funcs[i];
if (typeof func === 'function') {
translucent = translucent && func();
} else {
translucent = translucent && func;
}
if (!translucent) {
break;
}
}
return translucent;
};
/**
* @private
*/
Material.prototype.update = function(context) {
var i;
var uniformId;
var loadedImages = this._loadedImages;
var length = loadedImages.length;
for (i = 0; i < length; ++i) {
var loadedImage = loadedImages[i];
uniformId = loadedImage.id;
var image = loadedImage.image;
var texture;
if (defined(image.internalFormat)) {
texture = new Texture({
context : context,
pixelFormat : image.internalFormat,
width : image.width,
height : image.height,
source : {
arrayBufferView : image.bufferView
}
});
} else {
texture = new Texture({
context : context,
source : image
});
}
this._textures[uniformId] = texture;
var uniformDimensionsName = uniformId + 'Dimensions';
if (this.uniforms.hasOwnProperty(uniformDimensionsName)) {
var uniformDimensions = this.uniforms[uniformDimensionsName];
uniformDimensions.x = texture._width;
uniformDimensions.y = texture._height;
}
}
loadedImages.length = 0;
var loadedCubeMaps = this._loadedCubeMaps;
length = loadedCubeMaps.length;
for (i = 0; i < length; ++i) {
var loadedCubeMap = loadedCubeMaps[i];
uniformId = loadedCubeMap.id;
var images = loadedCubeMap.images;
var cubeMap = new CubeMap({
context : context,
source : {
positiveX : images[0],
negativeX : images[1],
positiveY : images[2],
negativeY : images[3],
positiveZ : images[4],
negativeZ : images[5]
}
});
this._textures[uniformId] = cubeMap;
}
loadedCubeMaps.length = 0;
var updateFunctions = this._updateFunctions;
length = updateFunctions.length;
for (i = 0; i < length; ++i) {
updateFunctions[i](this, context);
}
var subMaterials = this.materials;
for (var name in subMaterials) {
if (subMaterials.hasOwnProperty(name)) {
subMaterials[name].update(context);
}
}
};
/**
* Returns true if this object was destroyed; otherwise, false.
* <br /><br />
* If this object was destroyed, it should not be used; calling any function other than
* <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
*
* @returns {Boolean} True if this object was destroyed; otherwise, false.
*
* @see Material#destroy
*/
Material.prototype.isDestroyed = function() {
return false;
};
/**
* Destroys the WebGL resources held by this object. Destroying an object allows for deterministic
* release of WebGL resources, instead of relying on the garbage collector to destroy this object.
* <br /><br />
* Once an object is destroyed, it should not be used; calling any function other than
* <code>isDestroyed</code> will result in a {@link DeveloperError} exception. Therefore,
* assign the return value (<code>undefined</code>) to the object as done in the example.
*
* @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
*
*
* @example
* material = material && material.destroy();
*
* @see Material#isDestroyed
*/
Material.prototype.destroy = function() {
var textures = this._textures;
for ( var texture in textures) {
if (textures.hasOwnProperty(texture)) {
var instance = textures[texture];
if (instance !== this._defaultTexture) {
instance.destroy();
}
}
}
var materials = this.materials;
for ( var material in materials) {
if (materials.hasOwnProperty(material)) {
materials[material].destroy();
}
}
return destroyObject(this);
};
function initializeMaterial(options, result) {
options = defaultValue(options, defaultValue.EMPTY_OBJECT);
result._strict = defaultValue(options.strict, false);
result._count = defaultValue(options.count, 0);
result._template = clone(defaultValue(options.fabric, defaultValue.EMPTY_OBJECT));
result._template.uniforms = clone(defaultValue(result._template.uniforms, defaultValue.EMPTY_OBJECT));
result._template.materials = clone(defaultValue(result._template.materials, defaultValue.EMPTY_OBJECT));
result.type = defined(result._template.type) ? result._template.type : createGuid();
result.shaderSource = '';
result.materials = {};
result.uniforms = {};
result._uniforms = {};
result._translucentFunctions = [];
var translucent;
// If the cache contains this material type, build the material template off of the stored template.
var cachedMaterial = Material._materialCache.getMaterial(result.type);
if (defined(cachedMaterial)) {
var template = clone(cachedMaterial.fabric, true);
result._template = combine(result._template, template, true);
translucent = cachedMaterial.translucent;
}
// Make sure the template has no obvious errors. More error checking happens later.
checkForTemplateErrors(result);
// If the material has a new type, add it to the cache.
if (!defined(cachedMaterial)) {
Material._materialCache.addMaterial(result.type, result);
}
createMethodDefinition(result);
createUniforms(result);
createSubMaterials(result);
var defaultTranslucent = result._translucentFunctions.length === 0 ? true : undefined;
translucent = defaultValue(translucent, defaultTranslucent);
translucent = defaultValue(options.translucent, translucent);
if (defined(translucent)) {
if (typeof translucent === 'function') {
var wrappedTranslucent = function() {
return translucent(result);
};
result._translucentFunctions.push(wrappedTranslucent);
} else {
result._translucentFunctions.push(translucent);
}
}
}
function checkForValidProperties(object, properties, result, throwNotFound) {
if (defined(object)) {
for ( var property in object) {
if (object.hasOwnProperty(property)) {
var hasProperty = properties.indexOf(property) !== -1;
if ((throwNotFound && !hasProperty) || (!throwNotFound && hasProperty)) {
result(property, properties);
}
}
}
}
}
function invalidNameError(property, properties) {
//>>includeStart('debug', pragmas.debug);
var errorString = 'fabric: property name \'' + property + '\' is not valid. It should be ';
for ( var i = 0; i < properties.length; i++) {
var propertyName = '\'' + properties[i] + '\'';
errorString += (i === properties.length - 1) ? ('or ' + propertyName + '.') : (propertyName + ', ');
}
throw new DeveloperError(errorString);
//>>includeEnd('debug');
}
function duplicateNameError(property, properties) {
//>>includeStart('debug', pragmas.debug);
var errorString = 'fabric: uniforms and materials cannot share the same property \'' + property + '\'';
throw new DeveloperError(errorString);
//>>includeEnd('debug');
}
var templateProperties = ['type', 'materials', 'uniforms', 'components', 'source'];
var componentProperties = ['diffuse', 'specular', 'shininess', 'normal', 'emission', 'alpha'];
function checkForTemplateErrors(material) {
var template = material._template;
var uniforms = template.uniforms;
var materials = template.materials;
var components = template.components;
// Make sure source and components do not exist in the same template.
//>>includeStart('debug', pragmas.debug);
if (defined(components) && defined(template.source)) {
throw new DeveloperError('fabric: cannot have source and components in the same template.');
}
//>>includeEnd('debug');
// Make sure all template and components properties are valid.
checkForValidProperties(template, templateProperties, invalidNameError, true);
checkForValidProperties(components, componentProperties, invalidNameError, true);
// Make sure uniforms and materials do not share any of the same names.
var materialNames = [];
for ( var property in materials) {
if (materials.hasOwnProperty(property)) {
materialNames.push(property);
}
}
checkForValidProperties(uniforms, materialNames, duplicateNameError, false);
}
function isMaterialFused(shaderComponent, material) {
var materials = material._template.materials;
for (var subMaterialId in materials) {
if (materials.hasOwnProperty(subMaterialId)) {
if (shaderComponent.indexOf(subMaterialId) > -1) {
return true;
}
}
}
return false;
}
// Create the czm_getMaterial method body using source or components.
function createMethodDefinition(material) {
var components = material._template.components;
var source = material._template.source;
if (defined(source)) {
material.shaderSource += source + '\n';
} else {
material.shaderSource += 'czm_material czm_getMaterial(czm_materialInput materialInput)\n{\n';
material.shaderSource += 'czm_material material = czm_getDefaultMaterial(materialInput);\n';
if (defined(components)) {
var isMultiMaterial = Object.keys(material._template.materials).length > 0;
for ( var component in components) {
if (components.hasOwnProperty(component)) {
if (component === 'diffuse' || component === 'emission') {
var isFusion = isMultiMaterial && isMaterialFused(components[component], material);
var componentSource = isFusion ? components[component] : 'czm_gammaCorrect(' + components[component] + ')';
material.shaderSource += 'material.' + component + ' = ' + componentSource + '; \n';
} else if (component === 'alpha') {
material.shaderSource += 'material.alpha = ' + components.alpha + '; \n';
} else {
material.shaderSource += 'material.' + component + ' = ' + components[component] + ';\n';
}
}
}
}
material.shaderSource += 'return material;\n}\n';
}
}
var matrixMap = {
'mat2' : Matrix2,
'mat3' : Matrix3,
'mat4' : Matrix4
};
var ktxRegex = /\.ktx$/i;
var crnRegex = /\.crn$/i;
function createTexture2DUpdateFunction(uniformId) {
var oldUniformValue;
return function(material, context) {
var uniforms = material.uniforms;
var uniformValue = uniforms[uniformId];
var uniformChanged = oldUniformValue !== uniformValue;
oldUniformValue = uniformValue;
var texture = material._textures[uniformId];
var uniformDimensionsName;
var uniformDimensions;
if (uniformValue instanceof HTMLVideoElement) {
// HTMLVideoElement.readyState >=2 means we have enough data for the current frame.
// See: https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/readyState
if (uniformValue.readyState >= 2) {
if (uniformChanged && defined(texture)) {
if (texture !== context.defaultTexture) {
texture.destroy();
}
texture = undefined;
}
if (!defined(texture) || texture === context.defaultTexture) {
texture = new Texture({
context : context,
source : uniformValue
});
material._textures[uniformId] = texture;
return;
}
texture.copyFrom(uniformValue);
} else if (!defined(texture)) {
material._textures[uniformId] = context.defaultTexture;
}
return;
}
if (uniformValue instanceof Texture && uniformValue !== texture) {
material._texturePaths[uniformId] = undefined;
var tmp = material._textures[uniformId];
if (tmp !== material._defaultTexture) {
tmp.destroy();
}
material._textures[uniformId] = uniformValue;
uniformDimensionsName = uniformId + 'Dimensions';
if (uniforms.hasOwnProperty(uniformDimensionsName)) {
uniformDimensions = uniforms[uniformDimensionsName];
uniformDimensions.x = uniformValue._width;
uniformDimensions.y = uniformValue._height;
}
return;
}
if (!defined(texture)) {
material._texturePaths[uniformId] = undefined;
if (!defined(material._defaultTexture)) {
material._defaultTexture = context.defaultTexture;
}
texture = material._textures[uniformId] = material._defaultTexture;
uniformDimensionsName = uniformId + 'Dimensions';
if (uniforms.hasOwnProperty(uniformDimensionsName)) {
uniformDimensions = uniforms[uniformDimensionsName];
uniformDimensions.x = texture._width;
uniformDimensions.y = texture._height;
}
}
if (uniformValue === Material.DefaultImageId) {
return;
}
// When using the entity layer, the Resource objects get recreated on getValue because
// they are clonable. That's why we check the url property for Resources
// because the instances aren't the same and we keep trying to load the same
// image if it fails to load.
var isResource = (uniformValue instanceof Resource);
if (!defined(material._texturePaths[uniformId]) ||
(isResource && uniformValue.url !== material._texturePaths[uniformId].url) ||
(!isResource && uniformValue !== material._texturePaths[uniformId])) {
if (typeof uniformValue === 'string' || isResource) {
var resource = isResource ? uniformValue : Resource.createIfNeeded(uniformValue);
var promise;
if (ktxRegex.test(resource.url)) {
promise = loadKTX(resource);
} else if (crnRegex.test(resource.url)) {
promise = loadCRN(resource);
} else {
promise = resource.fetchImage();
}
when(promise, function(image) {
material._loadedImages.push({
id: uniformId,
image: image
});
});
} else if (uniformValue instanceof HTMLCanvasElement || uniformValue instanceof HTMLImageElement) {
material._loadedImages.push({
id: uniformId,
image: uniformValue
});
}
material._texturePaths[uniformId] = uniformValue;
}
};
}
function createCubeMapUpdateFunction(uniformId) {
return function(material, context) {
var uniformValue = material.uniforms[uniformId];
if (uniformValue instanceof CubeMap) {
var tmp = material._textures[uniformId];
if (tmp !== material._defaultTexture) {
tmp.destroy();
}
material._texturePaths[uniformId] = undefined;
material._textures[uniformId] = uniformValue;
return;
}
if (!defined(material._textures[uniformId])) {
material._texturePaths[uniformId] = undefined;
material._textures[uniformId] = context.defaultCubeMap;
}
if (uniformValue === Material.DefaultCubeMapId) {
return;
}
var path =
uniformValue.positiveX + uniformValue.negativeX +
uniformValue.positiveY + uniformValue.negativeY +
uniformValue.positiveZ + uniformValue.negativeZ;
if (path !== material._texturePaths[uniformId]) {
var promises = [
Resource.createIfNeeded(uniformValue.positiveX).fetchImage(),
Resource.createIfNeeded(uniformValue.negativeX).fetchImage(),
Resource.createIfNeeded(uniformValue.positiveY).fetchImage(),
Resource.createIfNeeded(uniformValue.negativeY).fetchImage(),
Resource.createIfNeeded(uniformValue.positiveZ).fetchImage(),
Resource.createIfNeeded(uniformValue.negativeZ).fetchImage()
];
when.all(promises).then(function(images) {
material._loadedCubeMaps.push({
id : uniformId,
images : images
});
});
material._texturePaths[uniformId] = path;
}
};
}
function createUniforms(material) {
var uniforms = material._template.uniforms;
for ( var uniformId in uniforms) {
if (uniforms.hasOwnProperty(uniformId)) {
createUniform(material, uniformId);
}
}
}
// Writes uniform declarations to the shader file and connects uniform values with
// corresponding material properties through the returnUniforms function.
function createUniform(material, uniformId) {
var strict = material._strict;
var materialUniforms = material._template.uniforms;
var uniformValue = materialUniforms[uniformId];
var uniformType = getUniformType(uniformValue);
//>>includeStart('debug', pragmas.debug);
if (!defined(uniformType)) {
throw new DeveloperError('fabric: uniform \'' + uniformId + '\' has invalid type.');
}
//>>includeEnd('debug');
var replacedTokenCount;
if (uniformType === 'channels') {
replacedTokenCount = replaceToken(material, uniformId, uniformValue, false);
//>>includeStart('debug', pragmas.debug);
if (replacedTokenCount === 0 && strict) {
throw new DeveloperError('strict: shader source does not use channels \'' + uniformId + '\'.');
}
//>>includeEnd('debug');
} else {
// Since webgl doesn't allow texture dimension queries in glsl, create a uniform to do it.
// Check if the shader source actually uses texture dimensions before creating the uniform.
if (uniformType === 'sampler2D') {
var imageDimensionsUniformName = uniformId + 'Dimensions';
if (getNumberOfTokens(material, imageDimensionsUniformName) > 0) {
materialUniforms[imageDimensionsUniformName] = {
type : 'ivec3',
x : 1,
y : 1
};
createUniform(material, imageDimensionsUniformName);
}
}
// Add uniform declaration to source code.
var uniformDeclarationRegex = new RegExp('uniform\\s+' + uniformType + '\\s+' + uniformId + '\\s*;');
if (!uniformDeclarationRegex.test(material.shaderSource)) {
var uniformDeclaration = 'uniform ' + uniformType + ' ' + uniformId + ';';
material.shaderSource = uniformDeclaration + material.shaderSource;
}
var newUniformId = uniformId + '_' + material._count++;
replacedTokenCount = replaceToken(material, uniformId, newUniformId);
//>>includeStart('debug', pragmas.debug);
if (replacedTokenCount === 1 && strict) {
throw new DeveloperError('strict: shader source does not use uniform \'' + uniformId + '\'.');
}
//>>includeEnd('debug');
// Set uniform value
material.uniforms[uniformId] = uniformValue;
if (uniformType === 'sampler2D') {
material._uniforms[newUniformId] = function() {
return material._textures[uniformId];
};
material._updateFunctions.push(createTexture2DUpdateFunction(uniformId));
} else if (uniformType === 'samplerCube') {
material._uniforms[newUniformId] = function() {
return material._textures[uniformId];
};
material._updateFunctions.push(createCubeMapUpdateFunction(uniformId));
} else if (uniformType.indexOf('mat') !== -1) {
var scratchMatrix = new matrixMap[uniformType]();
material._uniforms[newUniformId] = function() {
return matrixMap[uniformType].fromColumnMajorArray(material.uniforms[uniformId], scratchMatrix);
};
} else {
material._uniforms[newUniformId] = function() {
return material.uniforms[uniformId];
};
}
}
}
// Determines the uniform type based on the uniform in the template.
function getUniformType(uniformValue) {
var uniformType = uniformValue.type;
if (!defined(uniformType)) {
var type = typeof uniformValue;
if (type === 'number') {
uniformType = 'float';
} else if (type === 'boolean') {
uniformType = 'bool';
} else if (type === 'string' || uniformValue instanceof Resource ||uniformValue instanceof HTMLCanvasElement || uniformValue instanceof HTMLImageElement) {
if (/^([rgba]){1,4}$/i.test(uniformValue)) {
uniformType = 'channels';
} else if (uniformValue === Material.DefaultCubeMapId) {
uniformType = 'samplerCube';
} else {
uniformType = 'sampler2D';
}
} else if (type === 'object') {
if (isArray(uniformValue)) {
if (uniformValue.length === 4 || uniformValue.length === 9 || uniformValue.length === 16) {
uniformType = 'mat' + Math.sqrt(uniformValue.length);
}
} else {
var numAttributes = 0;
for ( var attribute in uniformValue) {
if (uniformValue.hasOwnProperty(attribute)) {
numAttributes += 1;
}
}
if (numAttributes >= 2 && numAttributes <= 4) {
uniformType = 'vec' + numAttributes;
} else if (numAttributes === 6) {
uniformType = 'samplerCube';
}
}
}
}
return uniformType;
}
// Create all sub-materials by combining source and uniforms together.
function createSubMaterials(material) {
var strict = material._strict;
var subMaterialTemplates = material._template.materials;
for ( var subMaterialId in subMaterialTemplates) {
if (subMaterialTemplates.hasOwnProperty(subMaterialId)) {
// Construct the sub-material.