Material.js 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694
  1. import Cartesian2 from "../Core/Cartesian2.js";
  2. import clone from "../Core/clone.js";
  3. import Color from "../Core/Color.js";
  4. import combine from "../Core/combine.js";
  5. import createGuid from "../Core/createGuid.js";
  6. import defaultValue from "../Core/defaultValue.js";
  7. import defined from "../Core/defined.js";
  8. import destroyObject from "../Core/destroyObject.js";
  9. import DeveloperError from "../Core/DeveloperError.js";
  10. import loadCRN from "../Core/loadCRN.js";
  11. import loadKTX from "../Core/loadKTX.js";
  12. import Matrix2 from "../Core/Matrix2.js";
  13. import Matrix3 from "../Core/Matrix3.js";
  14. import Matrix4 from "../Core/Matrix4.js";
  15. import Resource from "../Core/Resource.js";
  16. import CubeMap from "../Renderer/CubeMap.js";
  17. import Texture from "../Renderer/Texture.js";
  18. import AspectRampMaterial from "../Shaders/Materials/AspectRampMaterial.js";
  19. import BumpMapMaterial from "../Shaders/Materials/BumpMapMaterial.js";
  20. import CheckerboardMaterial from "../Shaders/Materials/CheckerboardMaterial.js";
  21. import DotMaterial from "../Shaders/Materials/DotMaterial.js";
  22. import ElevationContourMaterial from "../Shaders/Materials/ElevationContourMaterial.js";
  23. import ElevationRampMaterial from "../Shaders/Materials/ElevationRampMaterial.js";
  24. import FadeMaterial from "../Shaders/Materials/FadeMaterial.js";
  25. import GridMaterial from "../Shaders/Materials/GridMaterial.js";
  26. import NormalMapMaterial from "../Shaders/Materials/NormalMapMaterial.js";
  27. import PolylineArrowMaterial from "../Shaders/Materials/PolylineArrowMaterial.js";
  28. import PolylineDashMaterial from "../Shaders/Materials/PolylineDashMaterial.js";
  29. import PolylineGlowMaterial from "../Shaders/Materials/PolylineGlowMaterial.js";
  30. import PolylineOutlineMaterial from "../Shaders/Materials/PolylineOutlineMaterial.js";
  31. import RimLightingMaterial from "../Shaders/Materials/RimLightingMaterial.js";
  32. import Sampler from "../Renderer/Sampler.js";
  33. import SlopeRampMaterial from "../Shaders/Materials/SlopeRampMaterial.js";
  34. import StripeMaterial from "../Shaders/Materials/StripeMaterial.js";
  35. import TextureMagnificationFilter from "../Renderer/TextureMagnificationFilter.js";
  36. import TextureMinificationFilter from "../Renderer/TextureMinificationFilter.js";
  37. import WaterMaterial from "../Shaders/Materials/Water.js";
  38. import when from "../ThirdParty/when.js";
  39. /**
  40. * A Material defines surface appearance through a combination of diffuse, specular,
  41. * normal, emission, and alpha components. These values are specified using a
  42. * JSON schema called Fabric which gets parsed and assembled into glsl shader code
  43. * behind-the-scenes. Check out the {@link https://github.com/CesiumGS/cesium/wiki/Fabric|wiki page}
  44. * for more details on Fabric.
  45. * <br /><br />
  46. * <style type="text/css">
  47. * #materialDescriptions code {
  48. * font-weight: normal;
  49. * font-family: Consolas, 'Lucida Console', Monaco, monospace;
  50. * color: #A35A00;
  51. * }
  52. * #materialDescriptions ul, #materialDescriptions ul ul {
  53. * list-style-type: none;
  54. * }
  55. * #materialDescriptions ul ul {
  56. * margin-bottom: 10px;
  57. * }
  58. * #materialDescriptions ul ul li {
  59. * font-weight: normal;
  60. * color: #000000;
  61. * text-indent: -2em;
  62. * margin-left: 2em;
  63. * }
  64. * #materialDescriptions ul li {
  65. * font-weight: bold;
  66. * color: #0053CF;
  67. * }
  68. * </style>
  69. *
  70. * Base material types and their uniforms:
  71. * <div id='materialDescriptions'>
  72. * <ul>
  73. * <li>Color</li>
  74. * <ul>
  75. * <li><code>color</code>: rgba color object.</li>
  76. * </ul>
  77. * <li>Image</li>
  78. * <ul>
  79. * <li><code>image</code>: path to image.</li>
  80. * <li><code>repeat</code>: Object with x and y values specifying the number of times to repeat the image.</li>
  81. * </ul>
  82. * <li>DiffuseMap</li>
  83. * <ul>
  84. * <li><code>image</code>: path to image.</li>
  85. * <li><code>channels</code>: Three character string containing any combination of r, g, b, and a for selecting the desired image channels.</li>
  86. * <li><code>repeat</code>: Object with x and y values specifying the number of times to repeat the image.</li>
  87. * </ul>
  88. * <li>AlphaMap</li>
  89. * <ul>
  90. * <li><code>image</code>: path to image.</li>
  91. * <li><code>channel</code>: One character string containing r, g, b, or a for selecting the desired image channel. </li>
  92. * <li><code>repeat</code>: Object with x and y values specifying the number of times to repeat the image.</li>
  93. * </ul>
  94. * <li>SpecularMap</li>
  95. * <ul>
  96. * <li><code>image</code>: path to image.</li>
  97. * <li><code>channel</code>: One character string containing r, g, b, or a for selecting the desired image channel. </li>
  98. * <li><code>repeat</code>: Object with x and y values specifying the number of times to repeat the image.</li>
  99. * </ul>
  100. * <li>EmissionMap</li>
  101. * <ul>
  102. * <li><code>image</code>: path to image.</li>
  103. * <li><code>channels</code>: Three character string containing any combination of r, g, b, and a for selecting the desired image channels. </li>
  104. * <li><code>repeat</code>: Object with x and y values specifying the number of times to repeat the image.</li>
  105. * </ul>
  106. * <li>BumpMap</li>
  107. * <ul>
  108. * <li><code>image</code>: path to image.</li>
  109. * <li><code>channel</code>: One character string containing r, g, b, or a for selecting the desired image channel. </li>
  110. * <li><code>repeat</code>: Object with x and y values specifying the number of times to repeat the image.</li>
  111. * <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>
  112. * </ul>
  113. * <li>NormalMap</li>
  114. * <ul>
  115. * <li><code>image</code>: path to image.</li>
  116. * <li><code>channels</code>: Three character string containing any combination of r, g, b, and a for selecting the desired image channels. </li>
  117. * <li><code>repeat</code>: Object with x and y values specifying the number of times to repeat the image.</li>
  118. * <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>
  119. * </ul>
  120. * <li>Grid</li>
  121. * <ul>
  122. * <li><code>color</code>: rgba color object for the whole material.</li>
  123. * <li><code>cellAlpha</code>: Alpha value for the cells between grid lines. This will be combined with color.alpha.</li>
  124. * <li><code>lineCount</code>: Object with x and y values specifying the number of columns and rows respectively.</li>
  125. * <li><code>lineThickness</code>: Object with x and y values specifying the thickness of grid lines (in pixels where available).</li>
  126. * <li><code>lineOffset</code>: Object with x and y values specifying the offset of grid lines (range is 0 to 1).</li>
  127. * </ul>
  128. * <li>Stripe</li>
  129. * <ul>
  130. * <li><code>horizontal</code>: Boolean that determines if the stripes are horizontal or vertical.</li>
  131. * <li><code>evenColor</code>: rgba color object for the stripe's first color.</li>
  132. * <li><code>oddColor</code>: rgba color object for the stripe's second color.</li>
  133. * <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>
  134. * <li><code>repeat</code>: Number that controls the total number of stripes, half light and half dark.</li>
  135. * </ul>
  136. * <li>Checkerboard</li>
  137. * <ul>
  138. * <li><code>lightColor</code>: rgba color object for the checkerboard's light alternating color.</li>
  139. * <li><code>darkColor</code>: rgba color object for the checkerboard's dark alternating color.</li>
  140. * <li><code>repeat</code>: Object with x and y values specifying the number of columns and rows respectively.</li>
  141. * </ul>
  142. * <li>Dot</li>
  143. * <ul>
  144. * <li><code>lightColor</code>: rgba color object for the dot color.</li>
  145. * <li><code>darkColor</code>: rgba color object for the background color.</li>
  146. * <li><code>repeat</code>: Object with x and y values specifying the number of columns and rows of dots respectively.</li>
  147. * </ul>
  148. * <li>Water</li>
  149. * <ul>
  150. * <li><code>baseWaterColor</code>: rgba color object base color of the water.</li>
  151. * <li><code>blendColor</code>: rgba color object used when blending from water to non-water areas.</li>
  152. * <li><code>specularMap</code>: Single channel texture used to indicate areas of water.</li>
  153. * <li><code>normalMap</code>: Normal map for water normal perturbation.</li>
  154. * <li><code>frequency</code>: Number that controls the number of waves.</li>
  155. * <li><code>normalMap</code>: Normal map for water normal perturbation.</li>
  156. * <li><code>animationSpeed</code>: Number that controls the animations speed of the water.</li>
  157. * <li><code>amplitude</code>: Number that controls the amplitude of water waves.</li>
  158. * <li><code>specularIntensity</code>: Number that controls the intensity of specular reflections.</li>
  159. * </ul>
  160. * <li>RimLighting</li>
  161. * <ul>
  162. * <li><code>color</code>: diffuse color and alpha.</li>
  163. * <li><code>rimColor</code>: diffuse color and alpha of the rim.</li>
  164. * <li><code>width</code>: Number that determines the rim's width.</li>
  165. * </ul>
  166. * <li>Fade</li>
  167. * <ul>
  168. * <li><code>fadeInColor</code>: diffuse color and alpha at <code>time</code></li>
  169. * <li><code>fadeOutColor</code>: diffuse color and alpha at <code>maximumDistance</code> from <code>time</code></li>
  170. * <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>
  171. * <li><code>repeat</code>: true if the fade should wrap around the texture coodinates.</li>
  172. * <li><code>fadeDirection</code>: Object with x and y values specifying if the fade should be in the x and y directions.</li>
  173. * <li><code>time</code>: Object with x and y values between 0.0 and 1.0 of the <code>fadeInColor</code> position</li>
  174. * </ul>
  175. * <li>PolylineArrow</li>
  176. * <ul>
  177. * <li><code>color</code>: diffuse color and alpha.</li>
  178. * </ul>
  179. * <li>PolylineDash</li>
  180. * <ul>
  181. * <li><code>color</code>: color for the line.</li>
  182. * <li><code>gapColor</code>: color for the gaps in the line.</li>
  183. * <li><code>dashLength</code>: Dash length in pixels.</li>
  184. * <li><code>dashPattern</code>: The 16 bit stipple pattern for the line..</li>
  185. * </ul>
  186. * <li>PolylineGlow</li>
  187. * <ul>
  188. * <li><code>color</code>: color and maximum alpha for the glow on the line.</li>
  189. * <li><code>glowPower</code>: strength of the glow, as a percentage of the total line width (less than 1.0).</li>
  190. * <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>
  191. * </ul>
  192. * <li>PolylineOutline</li>
  193. * <ul>
  194. * <li><code>color</code>: diffuse color and alpha for the interior of the line.</li>
  195. * <li><code>outlineColor</code>: diffuse color and alpha for the outline.</li>
  196. * <li><code>outlineWidth</code>: width of the outline in pixels.</li>
  197. * </ul>
  198. * <li>ElevationContour</li>
  199. * <ul>
  200. * <li><code>color</code>: color and alpha for the contour line.</li>
  201. * <li><code>spacing</code>: spacing for contour lines in meters.</li>
  202. * <li><code>width</code>: Number specifying the width of the grid lines in pixels.</li>
  203. * </ul>
  204. * <li>ElevationRamp</li>
  205. * <ul>
  206. * <li><code>image</code>: color ramp image to use for coloring the terrain.</li>
  207. * <li><code>minimumHeight</code>: minimum height for the ramp.</li>
  208. * <li><code>maximumHeight</code>: maximum height for the ramp.</li>
  209. * </ul>
  210. * <li>SlopeRamp</li>
  211. * <ul>
  212. * <li><code>image</code>: color ramp image to use for coloring the terrain by slope.</li>
  213. * </ul>
  214. * <li>AspectRamp</li>
  215. * <ul>
  216. * <li><code>image</code>: color ramp image to use for color the terrain by aspect.</li>
  217. * </ul>
  218. * </ul>
  219. * </ul>
  220. * </div>
  221. *
  222. * @alias Material
  223. *
  224. * @param {Object} [options] Object with the following properties:
  225. * @param {Boolean} [options.strict=false] Throws errors for issues that would normally be ignored, including unused uniforms or materials.
  226. * @param {Boolean|Function} [options.translucent=true] When <code>true</code> or a function that returns <code>true</code>, the geometry
  227. * with this material is expected to appear translucent.
  228. * @param {TextureMinificationFilter} [options.minificationFilter=TextureMinificationFilter.LINEAR] The {@link TextureMinificationFilter} to apply to this material's textures.
  229. * @param {TextureMagnificationFilter} [options.magnificationFilter=TextureMagnificationFilter.LINEAR] The {@link TextureMagnificationFilter} to apply to this material's textures.
  230. * @param {Object} options.fabric The fabric JSON used to generate the material.
  231. *
  232. * @constructor
  233. *
  234. * @exception {DeveloperError} fabric: uniform has invalid type.
  235. * @exception {DeveloperError} fabric: uniforms and materials cannot share the same property.
  236. * @exception {DeveloperError} fabric: cannot have source and components in the same section.
  237. * @exception {DeveloperError} fabric: property name is not valid. It should be 'type', 'materials', 'uniforms', 'components', or 'source'.
  238. * @exception {DeveloperError} fabric: property name is not valid. It should be 'diffuse', 'specular', 'shininess', 'normal', 'emission', or 'alpha'.
  239. * @exception {DeveloperError} strict: shader source does not use string.
  240. * @exception {DeveloperError} strict: shader source does not use uniform.
  241. * @exception {DeveloperError} strict: shader source does not use material.
  242. *
  243. * @see {@link https://github.com/CesiumGS/cesium/wiki/Fabric|Fabric wiki page} for a more detailed options of Fabric.
  244. *
  245. * @demo {@link https://sandcastle.cesium.com/index.html?src=Materials.html|Cesium Sandcastle Materials Demo}
  246. *
  247. * @example
  248. * // Create a color material with fromType:
  249. * polygon.material = Cesium.Material.fromType('Color');
  250. * polygon.material.uniforms.color = new Cesium.Color(1.0, 1.0, 0.0, 1.0);
  251. *
  252. * // Create the default material:
  253. * polygon.material = new Cesium.Material();
  254. *
  255. * // Create a color material with full Fabric notation:
  256. * polygon.material = new Cesium.Material({
  257. * fabric : {
  258. * type : 'Color',
  259. * uniforms : {
  260. * color : new Cesium.Color(1.0, 1.0, 0.0, 1.0)
  261. * }
  262. * }
  263. * });
  264. */
  265. function Material(options) {
  266. /**
  267. * The material type. Can be an existing type or a new type. If no type is specified in fabric, type is a GUID.
  268. * @type {String}
  269. * @default undefined
  270. */
  271. this.type = undefined;
  272. /**
  273. * The glsl shader source for this material.
  274. * @type {String}
  275. * @default undefined
  276. */
  277. this.shaderSource = undefined;
  278. /**
  279. * Maps sub-material names to Material objects.
  280. * @type {Object}
  281. * @default undefined
  282. */
  283. this.materials = undefined;
  284. /**
  285. * Maps uniform names to their values.
  286. * @type {Object}
  287. * @default undefined
  288. */
  289. this.uniforms = undefined;
  290. this._uniforms = undefined;
  291. /**
  292. * When <code>true</code> or a function that returns <code>true</code>,
  293. * the geometry is expected to appear translucent.
  294. * @type {Boolean|Function}
  295. * @default undefined
  296. */
  297. this.translucent = undefined;
  298. this._minificationFilter = defaultValue(
  299. options.minificationFilter,
  300. TextureMinificationFilter.LINEAR
  301. );
  302. this._magnificationFilter = defaultValue(
  303. options.magnificationFilter,
  304. TextureMagnificationFilter.LINEAR
  305. );
  306. this._strict = undefined;
  307. this._template = undefined;
  308. this._count = undefined;
  309. this._texturePaths = {};
  310. this._loadedImages = [];
  311. this._loadedCubeMaps = [];
  312. this._textures = {};
  313. this._updateFunctions = [];
  314. this._defaultTexture = undefined;
  315. initializeMaterial(options, this);
  316. Object.defineProperties(this, {
  317. type: {
  318. value: this.type,
  319. writable: false,
  320. },
  321. });
  322. if (!defined(Material._uniformList[this.type])) {
  323. Material._uniformList[this.type] = Object.keys(this._uniforms);
  324. }
  325. }
  326. // Cached list of combined uniform names indexed by type.
  327. // Used to get the list of uniforms in the same order.
  328. Material._uniformList = {};
  329. /**
  330. * Creates a new material using an existing material type.
  331. * <br /><br />
  332. * Shorthand for: new Material({fabric : {type : type}});
  333. *
  334. * @param {String} type The base material type.
  335. * @param {Object} [uniforms] Overrides for the default uniforms.
  336. * @returns {Material} New material object.
  337. *
  338. * @exception {DeveloperError} material with that type does not exist.
  339. *
  340. * @example
  341. * var material = Cesium.Material.fromType('Color', {
  342. * color : new Cesium.Color(1.0, 0.0, 0.0, 1.0)
  343. * });
  344. */
  345. Material.fromType = function (type, uniforms) {
  346. //>>includeStart('debug', pragmas.debug);
  347. if (!defined(Material._materialCache.getMaterial(type))) {
  348. throw new DeveloperError(
  349. "material with type '" + type + "' does not exist."
  350. );
  351. }
  352. //>>includeEnd('debug');
  353. var material = new Material({
  354. fabric: {
  355. type: type,
  356. },
  357. });
  358. if (defined(uniforms)) {
  359. for (var name in uniforms) {
  360. if (uniforms.hasOwnProperty(name)) {
  361. material.uniforms[name] = uniforms[name];
  362. }
  363. }
  364. }
  365. return material;
  366. };
  367. /**
  368. * Gets whether or not this material is translucent.
  369. * @returns {Boolean} <code>true</code> if this material is translucent, <code>false</code> otherwise.
  370. */
  371. Material.prototype.isTranslucent = function () {
  372. if (defined(this.translucent)) {
  373. if (typeof this.translucent === "function") {
  374. return this.translucent();
  375. }
  376. return this.translucent;
  377. }
  378. var translucent = true;
  379. var funcs = this._translucentFunctions;
  380. var length = funcs.length;
  381. for (var i = 0; i < length; ++i) {
  382. var func = funcs[i];
  383. if (typeof func === "function") {
  384. translucent = translucent && func();
  385. } else {
  386. translucent = translucent && func;
  387. }
  388. if (!translucent) {
  389. break;
  390. }
  391. }
  392. return translucent;
  393. };
  394. /**
  395. * @private
  396. */
  397. Material.prototype.update = function (context) {
  398. var i;
  399. var uniformId;
  400. var loadedImages = this._loadedImages;
  401. var length = loadedImages.length;
  402. for (i = 0; i < length; ++i) {
  403. var loadedImage = loadedImages[i];
  404. uniformId = loadedImage.id;
  405. var image = loadedImage.image;
  406. var sampler = new Sampler({
  407. minificationFilter: this._minificationFilter,
  408. magnificationFilter: this._magnificationFilter,
  409. });
  410. var texture;
  411. if (defined(image.internalFormat)) {
  412. texture = new Texture({
  413. context: context,
  414. pixelFormat: image.internalFormat,
  415. width: image.width,
  416. height: image.height,
  417. source: {
  418. arrayBufferView: image.bufferView,
  419. },
  420. sampler: sampler,
  421. });
  422. } else {
  423. texture = new Texture({
  424. context: context,
  425. source: image,
  426. sampler: sampler,
  427. });
  428. }
  429. this._textures[uniformId] = texture;
  430. var uniformDimensionsName = uniformId + "Dimensions";
  431. if (this.uniforms.hasOwnProperty(uniformDimensionsName)) {
  432. var uniformDimensions = this.uniforms[uniformDimensionsName];
  433. uniformDimensions.x = texture._width;
  434. uniformDimensions.y = texture._height;
  435. }
  436. }
  437. loadedImages.length = 0;
  438. var loadedCubeMaps = this._loadedCubeMaps;
  439. length = loadedCubeMaps.length;
  440. for (i = 0; i < length; ++i) {
  441. var loadedCubeMap = loadedCubeMaps[i];
  442. uniformId = loadedCubeMap.id;
  443. var images = loadedCubeMap.images;
  444. var cubeMap = new CubeMap({
  445. context: context,
  446. source: {
  447. positiveX: images[0],
  448. negativeX: images[1],
  449. positiveY: images[2],
  450. negativeY: images[3],
  451. positiveZ: images[4],
  452. negativeZ: images[5],
  453. },
  454. sampler: new Sampler({
  455. minificationFilter: this._minificationFilter,
  456. magnificationFilter: this._magnificationFilter,
  457. }),
  458. });
  459. this._textures[uniformId] = cubeMap;
  460. }
  461. loadedCubeMaps.length = 0;
  462. var updateFunctions = this._updateFunctions;
  463. length = updateFunctions.length;
  464. for (i = 0; i < length; ++i) {
  465. updateFunctions[i](this, context);
  466. }
  467. var subMaterials = this.materials;
  468. for (var name in subMaterials) {
  469. if (subMaterials.hasOwnProperty(name)) {
  470. subMaterials[name].update(context);
  471. }
  472. }
  473. };
  474. /**
  475. * Returns true if this object was destroyed; otherwise, false.
  476. * <br /><br />
  477. * If this object was destroyed, it should not be used; calling any function other than
  478. * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
  479. *
  480. * @returns {Boolean} True if this object was destroyed; otherwise, false.
  481. *
  482. * @see Material#destroy
  483. */
  484. Material.prototype.isDestroyed = function () {
  485. return false;
  486. };
  487. /**
  488. * Destroys the WebGL resources held by this object. Destroying an object allows for deterministic
  489. * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
  490. * <br /><br />
  491. * Once an object is destroyed, it should not be used; calling any function other than
  492. * <code>isDestroyed</code> will result in a {@link DeveloperError} exception. Therefore,
  493. * assign the return value (<code>undefined</code>) to the object as done in the example.
  494. *
  495. * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
  496. *
  497. *
  498. * @example
  499. * material = material && material.destroy();
  500. *
  501. * @see Material#isDestroyed
  502. */
  503. Material.prototype.destroy = function () {
  504. var textures = this._textures;
  505. for (var texture in textures) {
  506. if (textures.hasOwnProperty(texture)) {
  507. var instance = textures[texture];
  508. if (instance !== this._defaultTexture) {
  509. instance.destroy();
  510. }
  511. }
  512. }
  513. var materials = this.materials;
  514. for (var material in materials) {
  515. if (materials.hasOwnProperty(material)) {
  516. materials[material].destroy();
  517. }
  518. }
  519. return destroyObject(this);
  520. };
  521. function initializeMaterial(options, result) {
  522. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  523. result._strict = defaultValue(options.strict, false);
  524. result._count = defaultValue(options.count, 0);
  525. result._template = clone(
  526. defaultValue(options.fabric, defaultValue.EMPTY_OBJECT)
  527. );
  528. result._template.uniforms = clone(
  529. defaultValue(result._template.uniforms, defaultValue.EMPTY_OBJECT)
  530. );
  531. result._template.materials = clone(
  532. defaultValue(result._template.materials, defaultValue.EMPTY_OBJECT)
  533. );
  534. result.type = defined(result._template.type)
  535. ? result._template.type
  536. : createGuid();
  537. result.shaderSource = "";
  538. result.materials = {};
  539. result.uniforms = {};
  540. result._uniforms = {};
  541. result._translucentFunctions = [];
  542. var translucent;
  543. // If the cache contains this material type, build the material template off of the stored template.
  544. var cachedMaterial = Material._materialCache.getMaterial(result.type);
  545. if (defined(cachedMaterial)) {
  546. var template = clone(cachedMaterial.fabric, true);
  547. result._template = combine(result._template, template, true);
  548. translucent = cachedMaterial.translucent;
  549. }
  550. // Make sure the template has no obvious errors. More error checking happens later.
  551. checkForTemplateErrors(result);
  552. // If the material has a new type, add it to the cache.
  553. if (!defined(cachedMaterial)) {
  554. Material._materialCache.addMaterial(result.type, result);
  555. }
  556. createMethodDefinition(result);
  557. createUniforms(result);
  558. createSubMaterials(result);
  559. var defaultTranslucent =
  560. result._translucentFunctions.length === 0 ? true : undefined;
  561. translucent = defaultValue(translucent, defaultTranslucent);
  562. translucent = defaultValue(options.translucent, translucent);
  563. if (defined(translucent)) {
  564. if (typeof translucent === "function") {
  565. var wrappedTranslucent = function () {
  566. return translucent(result);
  567. };
  568. result._translucentFunctions.push(wrappedTranslucent);
  569. } else {
  570. result._translucentFunctions.push(translucent);
  571. }
  572. }
  573. }
  574. function checkForValidProperties(object, properties, result, throwNotFound) {
  575. if (defined(object)) {
  576. for (var property in object) {
  577. if (object.hasOwnProperty(property)) {
  578. var hasProperty = properties.indexOf(property) !== -1;
  579. if (
  580. (throwNotFound && !hasProperty) ||
  581. (!throwNotFound && hasProperty)
  582. ) {
  583. result(property, properties);
  584. }
  585. }
  586. }
  587. }
  588. }
  589. function invalidNameError(property, properties) {
  590. //>>includeStart('debug', pragmas.debug);
  591. var errorString =
  592. "fabric: property name '" + property + "' is not valid. It should be ";
  593. for (var i = 0; i < properties.length; i++) {
  594. var propertyName = "'" + properties[i] + "'";
  595. errorString +=
  596. i === properties.length - 1
  597. ? "or " + propertyName + "."
  598. : propertyName + ", ";
  599. }
  600. throw new DeveloperError(errorString);
  601. //>>includeEnd('debug');
  602. }
  603. function duplicateNameError(property, properties) {
  604. //>>includeStart('debug', pragmas.debug);
  605. var errorString =
  606. "fabric: uniforms and materials cannot share the same property '" +
  607. property +
  608. "'";
  609. throw new DeveloperError(errorString);
  610. //>>includeEnd('debug');
  611. }
  612. var templateProperties = [
  613. "type",
  614. "materials",
  615. "uniforms",
  616. "components",
  617. "source",
  618. ];
  619. var componentProperties = [
  620. "diffuse",
  621. "specular",
  622. "shininess",
  623. "normal",
  624. "emission",
  625. "alpha",
  626. ];
  627. function checkForTemplateErrors(material) {
  628. var template = material._template;
  629. var uniforms = template.uniforms;
  630. var materials = template.materials;
  631. var components = template.components;
  632. // Make sure source and components do not exist in the same template.
  633. //>>includeStart('debug', pragmas.debug);
  634. if (defined(components) && defined(template.source)) {
  635. throw new DeveloperError(
  636. "fabric: cannot have source and components in the same template."
  637. );
  638. }
  639. //>>includeEnd('debug');
  640. // Make sure all template and components properties are valid.
  641. checkForValidProperties(template, templateProperties, invalidNameError, true);
  642. checkForValidProperties(
  643. components,
  644. componentProperties,
  645. invalidNameError,
  646. true
  647. );
  648. // Make sure uniforms and materials do not share any of the same names.
  649. var materialNames = [];
  650. for (var property in materials) {
  651. if (materials.hasOwnProperty(property)) {
  652. materialNames.push(property);
  653. }
  654. }
  655. checkForValidProperties(uniforms, materialNames, duplicateNameError, false);
  656. }
  657. function isMaterialFused(shaderComponent, material) {
  658. var materials = material._template.materials;
  659. for (var subMaterialId in materials) {
  660. if (materials.hasOwnProperty(subMaterialId)) {
  661. if (shaderComponent.indexOf(subMaterialId) > -1) {
  662. return true;
  663. }
  664. }
  665. }
  666. return false;
  667. }
  668. // Create the czm_getMaterial method body using source or components.
  669. function createMethodDefinition(material) {
  670. var components = material._template.components;
  671. var source = material._template.source;
  672. if (defined(source)) {
  673. material.shaderSource += source + "\n";
  674. } else {
  675. material.shaderSource +=
  676. "czm_material czm_getMaterial(czm_materialInput materialInput)\n{\n";
  677. material.shaderSource +=
  678. "czm_material material = czm_getDefaultMaterial(materialInput);\n";
  679. if (defined(components)) {
  680. var isMultiMaterial =
  681. Object.keys(material._template.materials).length > 0;
  682. for (var component in components) {
  683. if (components.hasOwnProperty(component)) {
  684. if (component === "diffuse" || component === "emission") {
  685. var isFusion =
  686. isMultiMaterial &&
  687. isMaterialFused(components[component], material);
  688. var componentSource = isFusion
  689. ? components[component]
  690. : "czm_gammaCorrect(" + components[component] + ")";
  691. material.shaderSource +=
  692. "material." + component + " = " + componentSource + "; \n";
  693. } else if (component === "alpha") {
  694. material.shaderSource +=
  695. "material.alpha = " + components.alpha + "; \n";
  696. } else {
  697. material.shaderSource +=
  698. "material." + component + " = " + components[component] + ";\n";
  699. }
  700. }
  701. }
  702. }
  703. material.shaderSource += "return material;\n}\n";
  704. }
  705. }
  706. var matrixMap = {
  707. mat2: Matrix2,
  708. mat3: Matrix3,
  709. mat4: Matrix4,
  710. };
  711. var ktxRegex = /\.ktx$/i;
  712. var crnRegex = /\.crn$/i;
  713. function createTexture2DUpdateFunction(uniformId) {
  714. var oldUniformValue;
  715. return function (material, context) {
  716. var uniforms = material.uniforms;
  717. var uniformValue = uniforms[uniformId];
  718. var uniformChanged = oldUniformValue !== uniformValue;
  719. oldUniformValue = uniformValue;
  720. var texture = material._textures[uniformId];
  721. var uniformDimensionsName;
  722. var uniformDimensions;
  723. if (uniformValue instanceof HTMLVideoElement) {
  724. // HTMLVideoElement.readyState >=2 means we have enough data for the current frame.
  725. // See: https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/readyState
  726. if (uniformValue.readyState >= 2) {
  727. if (uniformChanged && defined(texture)) {
  728. if (texture !== context.defaultTexture) {
  729. texture.destroy();
  730. }
  731. texture = undefined;
  732. }
  733. if (!defined(texture) || texture === context.defaultTexture) {
  734. var sampler = new Sampler({
  735. minificationFilter: material._minificationFilter,
  736. magnificationFilter: material._magnificationFilter,
  737. });
  738. texture = new Texture({
  739. context: context,
  740. source: uniformValue,
  741. sampler: sampler,
  742. });
  743. material._textures[uniformId] = texture;
  744. return;
  745. }
  746. texture.copyFrom(uniformValue);
  747. } else if (!defined(texture)) {
  748. material._textures[uniformId] = context.defaultTexture;
  749. }
  750. return;
  751. }
  752. if (uniformValue instanceof Texture && uniformValue !== texture) {
  753. material._texturePaths[uniformId] = undefined;
  754. var tmp = material._textures[uniformId];
  755. if (tmp !== material._defaultTexture) {
  756. tmp.destroy();
  757. }
  758. material._textures[uniformId] = uniformValue;
  759. uniformDimensionsName = uniformId + "Dimensions";
  760. if (uniforms.hasOwnProperty(uniformDimensionsName)) {
  761. uniformDimensions = uniforms[uniformDimensionsName];
  762. uniformDimensions.x = uniformValue._width;
  763. uniformDimensions.y = uniformValue._height;
  764. }
  765. return;
  766. }
  767. if (!defined(texture)) {
  768. material._texturePaths[uniformId] = undefined;
  769. if (!defined(material._defaultTexture)) {
  770. material._defaultTexture = context.defaultTexture;
  771. }
  772. texture = material._textures[uniformId] = material._defaultTexture;
  773. uniformDimensionsName = uniformId + "Dimensions";
  774. if (uniforms.hasOwnProperty(uniformDimensionsName)) {
  775. uniformDimensions = uniforms[uniformDimensionsName];
  776. uniformDimensions.x = texture._width;
  777. uniformDimensions.y = texture._height;
  778. }
  779. }
  780. if (uniformValue === Material.DefaultImageId) {
  781. return;
  782. }
  783. // When using the entity layer, the Resource objects get recreated on getValue because
  784. // they are clonable. That's why we check the url property for Resources
  785. // because the instances aren't the same and we keep trying to load the same
  786. // image if it fails to load.
  787. var isResource = uniformValue instanceof Resource;
  788. if (
  789. !defined(material._texturePaths[uniformId]) ||
  790. (isResource &&
  791. uniformValue.url !== material._texturePaths[uniformId].url) ||
  792. (!isResource && uniformValue !== material._texturePaths[uniformId])
  793. ) {
  794. if (typeof uniformValue === "string" || isResource) {
  795. var resource = isResource
  796. ? uniformValue
  797. : Resource.createIfNeeded(uniformValue);
  798. var promise;
  799. if (ktxRegex.test(resource.url)) {
  800. promise = loadKTX(resource);
  801. } else if (crnRegex.test(resource.url)) {
  802. promise = loadCRN(resource);
  803. } else {
  804. promise = resource.fetchImage();
  805. }
  806. when(promise, function (image) {
  807. material._loadedImages.push({
  808. id: uniformId,
  809. image: image,
  810. });
  811. });
  812. } else if (
  813. uniformValue instanceof HTMLCanvasElement ||
  814. uniformValue instanceof HTMLImageElement
  815. ) {
  816. material._loadedImages.push({
  817. id: uniformId,
  818. image: uniformValue,
  819. });
  820. }
  821. material._texturePaths[uniformId] = uniformValue;
  822. }
  823. };
  824. }
  825. function createCubeMapUpdateFunction(uniformId) {
  826. return function (material, context) {
  827. var uniformValue = material.uniforms[uniformId];
  828. if (uniformValue instanceof CubeMap) {
  829. var tmp = material._textures[uniformId];
  830. if (tmp !== material._defaultTexture) {
  831. tmp.destroy();
  832. }
  833. material._texturePaths[uniformId] = undefined;
  834. material._textures[uniformId] = uniformValue;
  835. return;
  836. }
  837. if (!defined(material._textures[uniformId])) {
  838. material._texturePaths[uniformId] = undefined;
  839. material._textures[uniformId] = context.defaultCubeMap;
  840. }
  841. if (uniformValue === Material.DefaultCubeMapId) {
  842. return;
  843. }
  844. var path =
  845. uniformValue.positiveX +
  846. uniformValue.negativeX +
  847. uniformValue.positiveY +
  848. uniformValue.negativeY +
  849. uniformValue.positiveZ +
  850. uniformValue.negativeZ;
  851. if (path !== material._texturePaths[uniformId]) {
  852. var promises = [
  853. Resource.createIfNeeded(uniformValue.positiveX).fetchImage(),
  854. Resource.createIfNeeded(uniformValue.negativeX).fetchImage(),
  855. Resource.createIfNeeded(uniformValue.positiveY).fetchImage(),
  856. Resource.createIfNeeded(uniformValue.negativeY).fetchImage(),
  857. Resource.createIfNeeded(uniformValue.positiveZ).fetchImage(),
  858. Resource.createIfNeeded(uniformValue.negativeZ).fetchImage(),
  859. ];
  860. when.all(promises).then(function (images) {
  861. material._loadedCubeMaps.push({
  862. id: uniformId,
  863. images: images,
  864. });
  865. });
  866. material._texturePaths[uniformId] = path;
  867. }
  868. };
  869. }
  870. function createUniforms(material) {
  871. var uniforms = material._template.uniforms;
  872. for (var uniformId in uniforms) {
  873. if (uniforms.hasOwnProperty(uniformId)) {
  874. createUniform(material, uniformId);
  875. }
  876. }
  877. }
  878. // Writes uniform declarations to the shader file and connects uniform values with
  879. // corresponding material properties through the returnUniforms function.
  880. function createUniform(material, uniformId) {
  881. var strict = material._strict;
  882. var materialUniforms = material._template.uniforms;
  883. var uniformValue = materialUniforms[uniformId];
  884. var uniformType = getUniformType(uniformValue);
  885. //>>includeStart('debug', pragmas.debug);
  886. if (!defined(uniformType)) {
  887. throw new DeveloperError(
  888. "fabric: uniform '" + uniformId + "' has invalid type."
  889. );
  890. }
  891. //>>includeEnd('debug');
  892. var replacedTokenCount;
  893. if (uniformType === "channels") {
  894. replacedTokenCount = replaceToken(material, uniformId, uniformValue, false);
  895. //>>includeStart('debug', pragmas.debug);
  896. if (replacedTokenCount === 0 && strict) {
  897. throw new DeveloperError(
  898. "strict: shader source does not use channels '" + uniformId + "'."
  899. );
  900. }
  901. //>>includeEnd('debug');
  902. } else {
  903. // Since webgl doesn't allow texture dimension queries in glsl, create a uniform to do it.
  904. // Check if the shader source actually uses texture dimensions before creating the uniform.
  905. if (uniformType === "sampler2D") {
  906. var imageDimensionsUniformName = uniformId + "Dimensions";
  907. if (getNumberOfTokens(material, imageDimensionsUniformName) > 0) {
  908. materialUniforms[imageDimensionsUniformName] = {
  909. type: "ivec3",
  910. x: 1,
  911. y: 1,
  912. };
  913. createUniform(material, imageDimensionsUniformName);
  914. }
  915. }
  916. // Add uniform declaration to source code.
  917. var uniformDeclarationRegex = new RegExp(
  918. "uniform\\s+" + uniformType + "\\s+" + uniformId + "\\s*;"
  919. );
  920. if (!uniformDeclarationRegex.test(material.shaderSource)) {
  921. var uniformDeclaration = "uniform " + uniformType + " " + uniformId + ";";
  922. material.shaderSource = uniformDeclaration + material.shaderSource;
  923. }
  924. var newUniformId = uniformId + "_" + material._count++;
  925. replacedTokenCount = replaceToken(material, uniformId, newUniformId);
  926. //>>includeStart('debug', pragmas.debug);
  927. if (replacedTokenCount === 1 && strict) {
  928. throw new DeveloperError(
  929. "strict: shader source does not use uniform '" + uniformId + "'."
  930. );
  931. }
  932. //>>includeEnd('debug');
  933. // Set uniform value
  934. material.uniforms[uniformId] = uniformValue;
  935. if (uniformType === "sampler2D") {
  936. material._uniforms[newUniformId] = function () {
  937. return material._textures[uniformId];
  938. };
  939. material._updateFunctions.push(createTexture2DUpdateFunction(uniformId));
  940. } else if (uniformType === "samplerCube") {
  941. material._uniforms[newUniformId] = function () {
  942. return material._textures[uniformId];
  943. };
  944. material._updateFunctions.push(createCubeMapUpdateFunction(uniformId));
  945. } else if (uniformType.indexOf("mat") !== -1) {
  946. var scratchMatrix = new matrixMap[uniformType]();
  947. material._uniforms[newUniformId] = function () {
  948. return matrixMap[uniformType].fromColumnMajorArray(
  949. material.uniforms[uniformId],
  950. scratchMatrix
  951. );
  952. };
  953. } else {
  954. material._uniforms[newUniformId] = function () {
  955. return material.uniforms[uniformId];
  956. };
  957. }
  958. }
  959. }
  960. // Determines the uniform type based on the uniform in the template.
  961. function getUniformType(uniformValue) {
  962. var uniformType = uniformValue.type;
  963. if (!defined(uniformType)) {
  964. var type = typeof uniformValue;
  965. if (type === "number") {
  966. uniformType = "float";
  967. } else if (type === "boolean") {
  968. uniformType = "bool";
  969. } else if (
  970. type === "string" ||
  971. uniformValue instanceof Resource ||
  972. uniformValue instanceof HTMLCanvasElement ||
  973. uniformValue instanceof HTMLImageElement
  974. ) {
  975. if (/^([rgba]){1,4}$/i.test(uniformValue)) {
  976. uniformType = "channels";
  977. } else if (uniformValue === Material.DefaultCubeMapId) {
  978. uniformType = "samplerCube";
  979. } else {
  980. uniformType = "sampler2D";
  981. }
  982. } else if (type === "object") {
  983. if (Array.isArray(uniformValue)) {
  984. if (
  985. uniformValue.length === 4 ||
  986. uniformValue.length === 9 ||
  987. uniformValue.length === 16
  988. ) {
  989. uniformType = "mat" + Math.sqrt(uniformValue.length);
  990. }
  991. } else {
  992. var numAttributes = 0;
  993. for (var attribute in uniformValue) {
  994. if (uniformValue.hasOwnProperty(attribute)) {
  995. numAttributes += 1;
  996. }
  997. }
  998. if (numAttributes >= 2 && numAttributes <= 4) {
  999. uniformType = "vec" + numAttributes;
  1000. } else if (numAttributes === 6) {
  1001. uniformType = "samplerCube";
  1002. }
  1003. }
  1004. }
  1005. }
  1006. return uniformType;
  1007. }
  1008. // Create all sub-materials by combining source and uniforms together.
  1009. function createSubMaterials(material) {
  1010. var strict = material._strict;
  1011. var subMaterialTemplates = material._template.materials;
  1012. for (var subMaterialId in subMaterialTemplates) {
  1013. if (subMaterialTemplates.hasOwnProperty(subMaterialId)) {
  1014. // Construct the sub-material.
  1015. var subMaterial = new Material({
  1016. strict: strict,
  1017. fabric: subMaterialTemplates[subMaterialId],
  1018. count: material._count,
  1019. });
  1020. material._count = subMaterial._count;
  1021. material._uniforms = combine(
  1022. material._uniforms,
  1023. subMaterial._uniforms,
  1024. true
  1025. );
  1026. material.materials[subMaterialId] = subMaterial;
  1027. material._translucentFunctions = material._translucentFunctions.concat(
  1028. subMaterial._translucentFunctions
  1029. );
  1030. // Make the material's czm_getMaterial unique by appending the sub-material type.
  1031. var originalMethodName = "czm_getMaterial";
  1032. var newMethodName = originalMethodName + "_" + material._count++;
  1033. replaceToken(subMaterial, originalMethodName, newMethodName);
  1034. material.shaderSource = subMaterial.shaderSource + material.shaderSource;
  1035. // Replace each material id with an czm_getMaterial method call.
  1036. var materialMethodCall = newMethodName + "(materialInput)";
  1037. var tokensReplacedCount = replaceToken(
  1038. material,
  1039. subMaterialId,
  1040. materialMethodCall
  1041. );
  1042. //>>includeStart('debug', pragmas.debug);
  1043. if (tokensReplacedCount === 0 && strict) {
  1044. throw new DeveloperError(
  1045. "strict: shader source does not use material '" + subMaterialId + "'."
  1046. );
  1047. }
  1048. //>>includeEnd('debug');
  1049. }
  1050. }
  1051. }
  1052. // Used for searching or replacing a token in a material's shader source with something else.
  1053. // If excludePeriod is true, do not accept tokens that are preceded by periods.
  1054. // http://stackoverflow.com/questions/641407/javascript-negative-lookbehind-equivalent
  1055. function replaceToken(material, token, newToken, excludePeriod) {
  1056. excludePeriod = defaultValue(excludePeriod, true);
  1057. var count = 0;
  1058. var suffixChars = "([\\w])?";
  1059. var prefixChars = "([\\w" + (excludePeriod ? "." : "") + "])?";
  1060. var regExp = new RegExp(prefixChars + token + suffixChars, "g");
  1061. material.shaderSource = material.shaderSource.replace(regExp, function (
  1062. $0,
  1063. $1,
  1064. $2
  1065. ) {
  1066. if ($1 || $2) {
  1067. return $0;
  1068. }
  1069. count += 1;
  1070. return newToken;
  1071. });
  1072. return count;
  1073. }
  1074. function getNumberOfTokens(material, token, excludePeriod) {
  1075. return replaceToken(material, token, token, excludePeriod);
  1076. }
  1077. Material._materialCache = {
  1078. _materials: {},
  1079. addMaterial: function (type, materialTemplate) {
  1080. this._materials[type] = materialTemplate;
  1081. },
  1082. getMaterial: function (type) {
  1083. return this._materials[type];
  1084. },
  1085. };
  1086. /**
  1087. * Gets or sets the default texture uniform value.
  1088. * @type {String}
  1089. */
  1090. Material.DefaultImageId = "czm_defaultImage";
  1091. /**
  1092. * Gets or sets the default cube map texture uniform value.
  1093. * @type {String}
  1094. */
  1095. Material.DefaultCubeMapId = "czm_defaultCubeMap";
  1096. /**
  1097. * Gets the name of the color material.
  1098. * @type {String}
  1099. * @readonly
  1100. */
  1101. Material.ColorType = "Color";
  1102. Material._materialCache.addMaterial(Material.ColorType, {
  1103. fabric: {
  1104. type: Material.ColorType,
  1105. uniforms: {
  1106. color: new Color(1.0, 0.0, 0.0, 0.5),
  1107. },
  1108. components: {
  1109. diffuse: "color.rgb",
  1110. alpha: "color.a",
  1111. },
  1112. },
  1113. translucent: function (material) {
  1114. return material.uniforms.color.alpha < 1.0;
  1115. },
  1116. });
  1117. /**
  1118. * Gets the name of the image material.
  1119. * @type {String}
  1120. * @readonly
  1121. */
  1122. Material.ImageType = "Image";
  1123. Material._materialCache.addMaterial(Material.ImageType, {
  1124. fabric: {
  1125. type: Material.ImageType,
  1126. uniforms: {
  1127. image: Material.DefaultImageId,
  1128. repeat: new Cartesian2(1.0, 1.0),
  1129. color: new Color(1.0, 1.0, 1.0, 1.0),
  1130. },
  1131. components: {
  1132. diffuse:
  1133. "texture2D(image, fract(repeat * materialInput.st)).rgb * color.rgb",
  1134. alpha: "texture2D(image, fract(repeat * materialInput.st)).a * color.a",
  1135. },
  1136. },
  1137. translucent: function (material) {
  1138. return material.uniforms.color.alpha < 1.0;
  1139. },
  1140. });
  1141. /**
  1142. * Gets the name of the diffuce map material.
  1143. * @type {String}
  1144. * @readonly
  1145. */
  1146. Material.DiffuseMapType = "DiffuseMap";
  1147. Material._materialCache.addMaterial(Material.DiffuseMapType, {
  1148. fabric: {
  1149. type: Material.DiffuseMapType,
  1150. uniforms: {
  1151. image: Material.DefaultImageId,
  1152. channels: "rgb",
  1153. repeat: new Cartesian2(1.0, 1.0),
  1154. },
  1155. components: {
  1156. diffuse: "texture2D(image, fract(repeat * materialInput.st)).channels",
  1157. },
  1158. },
  1159. translucent: false,
  1160. });
  1161. /**
  1162. * Gets the name of the alpha map material.
  1163. * @type {String}
  1164. * @readonly
  1165. */
  1166. Material.AlphaMapType = "AlphaMap";
  1167. Material._materialCache.addMaterial(Material.AlphaMapType, {
  1168. fabric: {
  1169. type: Material.AlphaMapType,
  1170. uniforms: {
  1171. image: Material.DefaultImageId,
  1172. channel: "a",
  1173. repeat: new Cartesian2(1.0, 1.0),
  1174. },
  1175. components: {
  1176. alpha: "texture2D(image, fract(repeat * materialInput.st)).channel",
  1177. },
  1178. },
  1179. translucent: true,
  1180. });
  1181. /**
  1182. * Gets the name of the specular map material.
  1183. * @type {String}
  1184. * @readonly
  1185. */
  1186. Material.SpecularMapType = "SpecularMap";
  1187. Material._materialCache.addMaterial(Material.SpecularMapType, {
  1188. fabric: {
  1189. type: Material.SpecularMapType,
  1190. uniforms: {
  1191. image: Material.DefaultImageId,
  1192. channel: "r",
  1193. repeat: new Cartesian2(1.0, 1.0),
  1194. },
  1195. components: {
  1196. specular: "texture2D(image, fract(repeat * materialInput.st)).channel",
  1197. },
  1198. },
  1199. translucent: false,
  1200. });
  1201. /**
  1202. * Gets the name of the emmision map material.
  1203. * @type {String}
  1204. * @readonly
  1205. */
  1206. Material.EmissionMapType = "EmissionMap";
  1207. Material._materialCache.addMaterial(Material.EmissionMapType, {
  1208. fabric: {
  1209. type: Material.EmissionMapType,
  1210. uniforms: {
  1211. image: Material.DefaultImageId,
  1212. channels: "rgb",
  1213. repeat: new Cartesian2(1.0, 1.0),
  1214. },
  1215. components: {
  1216. emission: "texture2D(image, fract(repeat * materialInput.st)).channels",
  1217. },
  1218. },
  1219. translucent: false,
  1220. });
  1221. /**
  1222. * Gets the name of the bump map material.
  1223. * @type {String}
  1224. * @readonly
  1225. */
  1226. Material.BumpMapType = "BumpMap";
  1227. Material._materialCache.addMaterial(Material.BumpMapType, {
  1228. fabric: {
  1229. type: Material.BumpMapType,
  1230. uniforms: {
  1231. image: Material.DefaultImageId,
  1232. channel: "r",
  1233. strength: 0.8,
  1234. repeat: new Cartesian2(1.0, 1.0),
  1235. },
  1236. source: BumpMapMaterial,
  1237. },
  1238. translucent: false,
  1239. });
  1240. /**
  1241. * Gets the name of the normal map material.
  1242. * @type {String}
  1243. * @readonly
  1244. */
  1245. Material.NormalMapType = "NormalMap";
  1246. Material._materialCache.addMaterial(Material.NormalMapType, {
  1247. fabric: {
  1248. type: Material.NormalMapType,
  1249. uniforms: {
  1250. image: Material.DefaultImageId,
  1251. channels: "rgb",
  1252. strength: 0.8,
  1253. repeat: new Cartesian2(1.0, 1.0),
  1254. },
  1255. source: NormalMapMaterial,
  1256. },
  1257. translucent: false,
  1258. });
  1259. /**
  1260. * Gets the name of the grid material.
  1261. * @type {String}
  1262. * @readonly
  1263. */
  1264. Material.GridType = "Grid";
  1265. Material._materialCache.addMaterial(Material.GridType, {
  1266. fabric: {
  1267. type: Material.GridType,
  1268. uniforms: {
  1269. color: new Color(0.0, 1.0, 0.0, 1.0),
  1270. cellAlpha: 0.1,
  1271. lineCount: new Cartesian2(8.0, 8.0),
  1272. lineThickness: new Cartesian2(1.0, 1.0),
  1273. lineOffset: new Cartesian2(0.0, 0.0),
  1274. },
  1275. source: GridMaterial,
  1276. },
  1277. translucent: function (material) {
  1278. var uniforms = material.uniforms;
  1279. return uniforms.color.alpha < 1.0 || uniforms.cellAlpha < 1.0;
  1280. },
  1281. });
  1282. /**
  1283. * Gets the name of the stripe material.
  1284. * @type {String}
  1285. * @readonly
  1286. */
  1287. Material.StripeType = "Stripe";
  1288. Material._materialCache.addMaterial(Material.StripeType, {
  1289. fabric: {
  1290. type: Material.StripeType,
  1291. uniforms: {
  1292. horizontal: true,
  1293. evenColor: new Color(1.0, 1.0, 1.0, 0.5),
  1294. oddColor: new Color(0.0, 0.0, 1.0, 0.5),
  1295. offset: 0.0,
  1296. repeat: 5.0,
  1297. },
  1298. source: StripeMaterial,
  1299. },
  1300. translucent: function (material) {
  1301. var uniforms = material.uniforms;
  1302. return uniforms.evenColor.alpha < 1.0 || uniforms.oddColor.alpha < 1.0;
  1303. },
  1304. });
  1305. /**
  1306. * Gets the name of the checkerboard material.
  1307. * @type {String}
  1308. * @readonly
  1309. */
  1310. Material.CheckerboardType = "Checkerboard";
  1311. Material._materialCache.addMaterial(Material.CheckerboardType, {
  1312. fabric: {
  1313. type: Material.CheckerboardType,
  1314. uniforms: {
  1315. lightColor: new Color(1.0, 1.0, 1.0, 0.5),
  1316. darkColor: new Color(0.0, 0.0, 0.0, 0.5),
  1317. repeat: new Cartesian2(5.0, 5.0),
  1318. },
  1319. source: CheckerboardMaterial,
  1320. },
  1321. translucent: function (material) {
  1322. var uniforms = material.uniforms;
  1323. return uniforms.lightColor.alpha < 1.0 || uniforms.darkColor.alpha < 1.0;
  1324. },
  1325. });
  1326. /**
  1327. * Gets the name of the dot material.
  1328. * @type {String}
  1329. * @readonly
  1330. */
  1331. Material.DotType = "Dot";
  1332. Material._materialCache.addMaterial(Material.DotType, {
  1333. fabric: {
  1334. type: Material.DotType,
  1335. uniforms: {
  1336. lightColor: new Color(1.0, 1.0, 0.0, 0.75),
  1337. darkColor: new Color(0.0, 1.0, 1.0, 0.75),
  1338. repeat: new Cartesian2(5.0, 5.0),
  1339. },
  1340. source: DotMaterial,
  1341. },
  1342. translucent: function (material) {
  1343. var uniforms = material.uniforms;
  1344. return uniforms.lightColor.alpha < 1.0 || uniforms.darkColor.alpha < 1.0;
  1345. },
  1346. });
  1347. /**
  1348. * Gets the name of the water material.
  1349. * @type {String}
  1350. * @readonly
  1351. */
  1352. Material.WaterType = "Water";
  1353. Material._materialCache.addMaterial(Material.WaterType, {
  1354. fabric: {
  1355. type: Material.WaterType,
  1356. uniforms: {
  1357. baseWaterColor: new Color(0.2, 0.3, 0.6, 1.0),
  1358. blendColor: new Color(0.0, 1.0, 0.699, 1.0),
  1359. specularMap: Material.DefaultImageId,
  1360. normalMap: Material.DefaultImageId,
  1361. frequency: 10.0,
  1362. animationSpeed: 0.01,
  1363. amplitude: 1.0,
  1364. specularIntensity: 0.5,
  1365. fadeFactor: 1.0,
  1366. },
  1367. source: WaterMaterial,
  1368. },
  1369. translucent: function (material) {
  1370. var uniforms = material.uniforms;
  1371. return (
  1372. uniforms.baseWaterColor.alpha < 1.0 || uniforms.blendColor.alpha < 1.0
  1373. );
  1374. },
  1375. });
  1376. /**
  1377. * Gets the name of the rim lighting material.
  1378. * @type {String}
  1379. * @readonly
  1380. */
  1381. Material.RimLightingType = "RimLighting";
  1382. Material._materialCache.addMaterial(Material.RimLightingType, {
  1383. fabric: {
  1384. type: Material.RimLightingType,
  1385. uniforms: {
  1386. color: new Color(1.0, 0.0, 0.0, 0.7),
  1387. rimColor: new Color(1.0, 1.0, 1.0, 0.4),
  1388. width: 0.3,
  1389. },
  1390. source: RimLightingMaterial,
  1391. },
  1392. translucent: function (material) {
  1393. var uniforms = material.uniforms;
  1394. return uniforms.color.alpha < 1.0 || uniforms.rimColor.alpha < 1.0;
  1395. },
  1396. });
  1397. /**
  1398. * Gets the name of the fade material.
  1399. * @type {String}
  1400. * @readonly
  1401. */
  1402. Material.FadeType = "Fade";
  1403. Material._materialCache.addMaterial(Material.FadeType, {
  1404. fabric: {
  1405. type: Material.FadeType,
  1406. uniforms: {
  1407. fadeInColor: new Color(1.0, 0.0, 0.0, 1.0),
  1408. fadeOutColor: new Color(0.0, 0.0, 0.0, 0.0),
  1409. maximumDistance: 0.5,
  1410. repeat: true,
  1411. fadeDirection: {
  1412. x: true,
  1413. y: true,
  1414. },
  1415. time: new Cartesian2(0.5, 0.5),
  1416. },
  1417. source: FadeMaterial,
  1418. },
  1419. translucent: function (material) {
  1420. var uniforms = material.uniforms;
  1421. return (
  1422. uniforms.fadeInColor.alpha < 1.0 || uniforms.fadeOutColor.alpha < 1.0
  1423. );
  1424. },
  1425. });
  1426. /**
  1427. * Gets the name of the polyline arrow material.
  1428. * @type {String}
  1429. * @readonly
  1430. */
  1431. Material.PolylineArrowType = "PolylineArrow";
  1432. Material._materialCache.addMaterial(Material.PolylineArrowType, {
  1433. fabric: {
  1434. type: Material.PolylineArrowType,
  1435. uniforms: {
  1436. color: new Color(1.0, 1.0, 1.0, 1.0),
  1437. },
  1438. source: PolylineArrowMaterial,
  1439. },
  1440. translucent: true,
  1441. });
  1442. /**
  1443. * Gets the name of the polyline glow material.
  1444. * @type {String}
  1445. * @readonly
  1446. */
  1447. Material.PolylineDashType = "PolylineDash";
  1448. Material._materialCache.addMaterial(Material.PolylineDashType, {
  1449. fabric: {
  1450. type: Material.PolylineDashType,
  1451. uniforms: {
  1452. color: new Color(1.0, 0.0, 1.0, 1.0),
  1453. gapColor: new Color(0.0, 0.0, 0.0, 0.0),
  1454. dashLength: 16.0,
  1455. dashPattern: 255.0,
  1456. },
  1457. source: PolylineDashMaterial,
  1458. },
  1459. translucent: true,
  1460. });
  1461. /**
  1462. * Gets the name of the polyline glow material.
  1463. * @type {String}
  1464. * @readonly
  1465. */
  1466. Material.PolylineGlowType = "PolylineGlow";
  1467. Material._materialCache.addMaterial(Material.PolylineGlowType, {
  1468. fabric: {
  1469. type: Material.PolylineGlowType,
  1470. uniforms: {
  1471. color: new Color(0.0, 0.5, 1.0, 1.0),
  1472. glowPower: 0.25,
  1473. taperPower: 1.0,
  1474. },
  1475. source: PolylineGlowMaterial,
  1476. },
  1477. translucent: true,
  1478. });
  1479. /**
  1480. * Gets the name of the polyline outline material.
  1481. * @type {String}
  1482. * @readonly
  1483. */
  1484. Material.PolylineOutlineType = "PolylineOutline";
  1485. Material._materialCache.addMaterial(Material.PolylineOutlineType, {
  1486. fabric: {
  1487. type: Material.PolylineOutlineType,
  1488. uniforms: {
  1489. color: new Color(1.0, 1.0, 1.0, 1.0),
  1490. outlineColor: new Color(1.0, 0.0, 0.0, 1.0),
  1491. outlineWidth: 1.0,
  1492. },
  1493. source: PolylineOutlineMaterial,
  1494. },
  1495. translucent: function (material) {
  1496. var uniforms = material.uniforms;
  1497. return uniforms.color.alpha < 1.0 || uniforms.outlineColor.alpha < 1.0;
  1498. },
  1499. });
  1500. /**
  1501. * Gets the name of the elevation contour material.
  1502. * @type {String}
  1503. * @readonly
  1504. */
  1505. Material.ElevationContourType = "ElevationContour";
  1506. Material._materialCache.addMaterial(Material.ElevationContourType, {
  1507. fabric: {
  1508. type: Material.ElevationContourType,
  1509. uniforms: {
  1510. spacing: 100.0,
  1511. color: new Color(1.0, 0.0, 0.0, 1.0),
  1512. width: 1.0,
  1513. },
  1514. source: ElevationContourMaterial,
  1515. },
  1516. translucent: false,
  1517. });
  1518. /**
  1519. * Gets the name of the elevation contour material.
  1520. * @type {String}
  1521. * @readonly
  1522. */
  1523. Material.ElevationRampType = "ElevationRamp";
  1524. Material._materialCache.addMaterial(Material.ElevationRampType, {
  1525. fabric: {
  1526. type: Material.ElevationRampType,
  1527. uniforms: {
  1528. image: Material.DefaultImageId,
  1529. minimumHeight: 0.0,
  1530. maximumHeight: 10000.0,
  1531. },
  1532. source: ElevationRampMaterial,
  1533. },
  1534. translucent: false,
  1535. });
  1536. /**
  1537. * Gets the name of the slope ramp material.
  1538. * @type {String}
  1539. * @readonly
  1540. */
  1541. Material.SlopeRampMaterialType = "SlopeRamp";
  1542. Material._materialCache.addMaterial(Material.SlopeRampMaterialType, {
  1543. fabric: {
  1544. type: Material.SlopeRampMaterialType,
  1545. uniforms: {
  1546. image: Material.DefaultImageId,
  1547. },
  1548. source: SlopeRampMaterial,
  1549. },
  1550. translucent: false,
  1551. });
  1552. /**
  1553. * Gets the name of the aspect ramp material.
  1554. * @type {String}
  1555. * @readonly
  1556. */
  1557. Material.AspectRampMaterialType = "AspectRamp";
  1558. Material._materialCache.addMaterial(Material.AspectRampMaterialType, {
  1559. fabric: {
  1560. type: Material.AspectRampMaterialType,
  1561. uniforms: {
  1562. image: Material.DefaultImageId,
  1563. },
  1564. source: AspectRampMaterial,
  1565. },
  1566. translucent: false,
  1567. });
  1568. export default Material;