effect.ts 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506
  1. import { Observable, Tools } from "Tools";
  2. import { Nullable } from "types";
  3. import { Matrix, Vector3, Vector2, Color3, Color4, Vector4 } from "Math";
  4. import { Engine } from "Engine";
  5. import { AbstractMesh } from "Mesh";
  6. import { RenderTargetTexture, Material, InternalTexture, BaseTexture } from "Materials";
  7. import { PostProcess } from "PostProcess";
  8. /**
  9. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  10. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  11. */
  12. export class EffectFallbacks {
  13. private _defines: { [key: string]: Array<String> } = {};
  14. private _currentRank = 32;
  15. private _maxRank = -1;
  16. private _mesh: Nullable<AbstractMesh>;
  17. /**
  18. * Removes the fallback from the bound mesh.
  19. */
  20. public unBindMesh() {
  21. this._mesh = null;
  22. }
  23. /**
  24. * Adds a fallback on the specified property.
  25. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  26. * @param define The name of the define in the shader
  27. */
  28. public addFallback(rank: number, define: string): void {
  29. if (!this._defines[rank]) {
  30. if (rank < this._currentRank) {
  31. this._currentRank = rank;
  32. }
  33. if (rank > this._maxRank) {
  34. this._maxRank = rank;
  35. }
  36. this._defines[rank] = new Array<String>();
  37. }
  38. this._defines[rank].push(define);
  39. }
  40. /**
  41. * Sets the mesh to use CPU skinning when needing to fallback.
  42. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  43. * @param mesh The mesh to use the fallbacks.
  44. */
  45. public addCPUSkinningFallback(rank: number, mesh: AbstractMesh) {
  46. this._mesh = mesh;
  47. if (rank < this._currentRank) {
  48. this._currentRank = rank;
  49. }
  50. if (rank > this._maxRank) {
  51. this._maxRank = rank;
  52. }
  53. }
  54. /**
  55. * Checks to see if more fallbacks are still availible.
  56. */
  57. public get isMoreFallbacks(): boolean {
  58. return this._currentRank <= this._maxRank;
  59. }
  60. /**
  61. * Removes the defines that shoould be removed when falling back.
  62. * @param currentDefines defines the current define statements for the shader.
  63. * @param effect defines the current effect we try to compile
  64. * @returns The resulting defines with defines of the current rank removed.
  65. */
  66. public reduce(currentDefines: string, effect: Effect): string {
  67. // First we try to switch to CPU skinning
  68. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  69. this._mesh.computeBonesUsingShaders = false;
  70. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  71. effect._bonesComputationForcedToCPU = true;
  72. var scene = this._mesh.getScene();
  73. for (var index = 0; index < scene.meshes.length; index++) {
  74. var otherMesh = scene.meshes[index];
  75. if (!otherMesh.material) {
  76. continue;
  77. }
  78. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  79. continue;
  80. }
  81. if (otherMesh.material.getEffect() === effect) {
  82. otherMesh.computeBonesUsingShaders = false;
  83. } else if (otherMesh.subMeshes) {
  84. for (var subMesh of otherMesh.subMeshes) {
  85. let subMeshEffect = subMesh.effect;
  86. if (subMeshEffect === effect) {
  87. otherMesh.computeBonesUsingShaders = false;
  88. break;
  89. }
  90. }
  91. }
  92. }
  93. }
  94. else {
  95. var currentFallbacks = this._defines[this._currentRank];
  96. if (currentFallbacks) {
  97. for (var index = 0; index < currentFallbacks.length; index++) {
  98. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  99. }
  100. }
  101. this._currentRank++;
  102. }
  103. return currentDefines;
  104. }
  105. }
  106. /**
  107. * Options to be used when creating an effect.
  108. */
  109. export class EffectCreationOptions {
  110. /**
  111. * Atrributes that will be used in the shader.
  112. */
  113. public attributes: string[];
  114. /**
  115. * Uniform varible names that will be set in the shader.
  116. */
  117. public uniformsNames: string[];
  118. /**
  119. * Uniform buffer varible names that will be set in the shader.
  120. */
  121. public uniformBuffersNames: string[];
  122. /**
  123. * Sampler texture variable names that will be set in the shader.
  124. */
  125. public samplers: string[];
  126. /**
  127. * Define statements that will be set in the shader.
  128. */
  129. public defines: any;
  130. /**
  131. * Possible fallbacks for this effect to improve performance when needed.
  132. */
  133. public fallbacks: Nullable<EffectFallbacks>;
  134. /**
  135. * Callback that will be called when the shader is compiled.
  136. */
  137. public onCompiled: Nullable<(effect: Effect) => void>;
  138. /**
  139. * Callback that will be called if an error occurs during shader compilation.
  140. */
  141. public onError: Nullable<(effect: Effect, errors: string) => void>;
  142. /**
  143. * Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  144. */
  145. public indexParameters: any;
  146. /**
  147. * Max number of lights that can be used in the shader.
  148. */
  149. public maxSimultaneousLights: number;
  150. /**
  151. * See https://developer.mozilla.org/en-US/docs/Web/API/WebGL2RenderingContext/transformFeedbackVaryings
  152. */
  153. public transformFeedbackVaryings: Nullable<string[]>;
  154. }
  155. /**
  156. * Effect containing vertex and fragment shader that can be executed on an object.
  157. */
  158. export class Effect {
  159. /**
  160. * Name of the effect.
  161. */
  162. public name: any;
  163. /**
  164. * String container all the define statements that should be set on the shader.
  165. */
  166. public defines: string;
  167. /**
  168. * Callback that will be called when the shader is compiled.
  169. */
  170. public onCompiled: Nullable<(effect: Effect) => void>;
  171. /**
  172. * Callback that will be called if an error occurs during shader compilation.
  173. */
  174. public onError: Nullable<(effect: Effect, errors: string) => void>;
  175. /**
  176. * Callback that will be called when effect is bound.
  177. */
  178. public onBind: Nullable<(effect: Effect) => void>;
  179. /**
  180. * Unique ID of the effect.
  181. */
  182. public uniqueId = 0;
  183. /**
  184. * Observable that will be called when the shader is compiled.
  185. * It is recommended to use executeWhenCompile() or to make sure that scene.isReady() is called to get this observable raised.
  186. */
  187. public onCompileObservable = new Observable<Effect>();
  188. /**
  189. * Observable that will be called if an error occurs during shader compilation.
  190. */
  191. public onErrorObservable = new Observable<Effect>();
  192. /** @hidden */
  193. public _onBindObservable: Nullable<Observable<Effect>>;
  194. /**
  195. * Observable that will be called when effect is bound.
  196. */
  197. public get onBindObservable(): Observable<Effect> {
  198. if (!this._onBindObservable) {
  199. this._onBindObservable = new Observable<Effect>();
  200. }
  201. return this._onBindObservable;
  202. }
  203. /** @hidden */
  204. public _bonesComputationForcedToCPU = false;
  205. private static _uniqueIdSeed = 0;
  206. private _engine: Engine;
  207. private _uniformBuffersNames: { [key: string]: number } = {};
  208. private _uniformsNames: string[];
  209. private _samplers: string[];
  210. private _isReady = false;
  211. private _compilationError = "";
  212. private _attributesNames: string[];
  213. private _attributes: number[];
  214. private _uniforms: Nullable<WebGLUniformLocation>[];
  215. /**
  216. * Key for the effect.
  217. * @hidden
  218. */
  219. public _key: string;
  220. private _indexParameters: any;
  221. private _fallbacks: Nullable<EffectFallbacks>;
  222. private _vertexSourceCode: string;
  223. private _fragmentSourceCode: string;
  224. private _vertexSourceCodeOverride: string;
  225. private _fragmentSourceCodeOverride: string;
  226. private _transformFeedbackVaryings: Nullable<string[]>;
  227. /**
  228. * Compiled shader to webGL program.
  229. * @hidden
  230. */
  231. public _program: WebGLProgram;
  232. private _valueCache: { [key: string]: any };
  233. private static _baseCache: { [key: number]: WebGLBuffer } = {};
  234. /**
  235. * Instantiates an effect.
  236. * An effect can be used to create/manage/execute vertex and fragment shaders.
  237. * @param baseName Name of the effect.
  238. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  239. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  240. * @param samplers List of sampler variables that will be passed to the shader.
  241. * @param engine Engine to be used to render the effect
  242. * @param defines Define statements to be added to the shader.
  243. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  244. * @param onCompiled Callback that will be called when the shader is compiled.
  245. * @param onError Callback that will be called if an error occurs during shader compilation.
  246. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  247. */
  248. constructor(baseName: any, attributesNamesOrOptions: string[] | EffectCreationOptions, uniformsNamesOrEngine: string[] | Engine, samplers: Nullable<string[]> = null, engine?: Engine, defines: Nullable<string> = null,
  249. fallbacks: Nullable<EffectFallbacks> = null, onCompiled: Nullable<(effect: Effect) => void> = null, onError: Nullable<(effect: Effect, errors: string) => void> = null, indexParameters?: any) {
  250. this.name = baseName;
  251. if ((<EffectCreationOptions>attributesNamesOrOptions).attributes) {
  252. var options = <EffectCreationOptions>attributesNamesOrOptions;
  253. this._engine = <Engine>uniformsNamesOrEngine;
  254. this._attributesNames = options.attributes;
  255. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  256. this._samplers = options.samplers.slice();
  257. this.defines = options.defines;
  258. this.onError = options.onError;
  259. this.onCompiled = options.onCompiled;
  260. this._fallbacks = options.fallbacks;
  261. this._indexParameters = options.indexParameters;
  262. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  263. if (options.uniformBuffersNames) {
  264. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  265. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  266. }
  267. }
  268. } else {
  269. this._engine = <Engine>engine;
  270. this.defines = <string>defines;
  271. this._uniformsNames = (<string[]>uniformsNamesOrEngine).concat(<string[]>samplers);
  272. this._samplers = samplers ? <string[]>samplers.slice() : [];
  273. this._attributesNames = (<string[]>attributesNamesOrOptions);
  274. this.onError = onError;
  275. this.onCompiled = onCompiled;
  276. this._indexParameters = indexParameters;
  277. this._fallbacks = fallbacks;
  278. }
  279. this.uniqueId = Effect._uniqueIdSeed++;
  280. var vertexSource: any;
  281. var fragmentSource: any;
  282. if (baseName.vertexElement) {
  283. vertexSource = document.getElementById(baseName.vertexElement);
  284. if (!vertexSource) {
  285. vertexSource = baseName.vertexElement;
  286. }
  287. } else {
  288. vertexSource = baseName.vertex || baseName;
  289. }
  290. if (baseName.fragmentElement) {
  291. fragmentSource = document.getElementById(baseName.fragmentElement);
  292. if (!fragmentSource) {
  293. fragmentSource = baseName.fragmentElement;
  294. }
  295. } else {
  296. fragmentSource = baseName.fragment || baseName;
  297. }
  298. this._loadVertexShader(vertexSource, (vertexCode) => {
  299. this._processIncludes(vertexCode, (vertexCodeWithIncludes) => {
  300. this._processShaderConversion(vertexCodeWithIncludes, false, (migratedVertexCode) => {
  301. this._loadFragmentShader(fragmentSource, (fragmentCode) => {
  302. this._processIncludes(fragmentCode, (fragmentCodeWithIncludes) => {
  303. this._processShaderConversion(fragmentCodeWithIncludes, true, (migratedFragmentCode) => {
  304. if (baseName) {
  305. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  306. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  307. this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  308. this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  309. } else {
  310. this._vertexSourceCode = migratedVertexCode;
  311. this._fragmentSourceCode = migratedFragmentCode;
  312. }
  313. this._prepareEffect();
  314. });
  315. });
  316. });
  317. });
  318. });
  319. });
  320. }
  321. /**
  322. * Unique key for this effect
  323. */
  324. public get key(): string {
  325. return this._key;
  326. }
  327. /**
  328. * If the effect has been compiled and prepared.
  329. * @returns if the effect is compiled and prepared.
  330. */
  331. public isReady(): boolean {
  332. if (!this._isReady && this._program && this._program.isParallelCompiled) {
  333. return this._engine._isProgramCompiled(this._program);
  334. }
  335. return this._isReady;
  336. }
  337. /**
  338. * The engine the effect was initialized with.
  339. * @returns the engine.
  340. */
  341. public getEngine(): Engine {
  342. return this._engine;
  343. }
  344. /**
  345. * The compiled webGL program for the effect
  346. * @returns the webGL program.
  347. */
  348. public getProgram(): WebGLProgram {
  349. return this._program;
  350. }
  351. /**
  352. * The set of names of attribute variables for the shader.
  353. * @returns An array of attribute names.
  354. */
  355. public getAttributesNames(): string[] {
  356. return this._attributesNames;
  357. }
  358. /**
  359. * Returns the attribute at the given index.
  360. * @param index The index of the attribute.
  361. * @returns The location of the attribute.
  362. */
  363. public getAttributeLocation(index: number): number {
  364. return this._attributes[index];
  365. }
  366. /**
  367. * Returns the attribute based on the name of the variable.
  368. * @param name of the attribute to look up.
  369. * @returns the attribute location.
  370. */
  371. public getAttributeLocationByName(name: string): number {
  372. var index = this._attributesNames.indexOf(name);
  373. return this._attributes[index];
  374. }
  375. /**
  376. * The number of attributes.
  377. * @returns the numnber of attributes.
  378. */
  379. public getAttributesCount(): number {
  380. return this._attributes.length;
  381. }
  382. /**
  383. * Gets the index of a uniform variable.
  384. * @param uniformName of the uniform to look up.
  385. * @returns the index.
  386. */
  387. public getUniformIndex(uniformName: string): number {
  388. return this._uniformsNames.indexOf(uniformName);
  389. }
  390. /**
  391. * Returns the attribute based on the name of the variable.
  392. * @param uniformName of the uniform to look up.
  393. * @returns the location of the uniform.
  394. */
  395. public getUniform(uniformName: string): Nullable<WebGLUniformLocation> {
  396. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  397. }
  398. /**
  399. * Returns an array of sampler variable names
  400. * @returns The array of sampler variable neames.
  401. */
  402. public getSamplers(): string[] {
  403. return this._samplers;
  404. }
  405. /**
  406. * The error from the last compilation.
  407. * @returns the error string.
  408. */
  409. public getCompilationError(): string {
  410. return this._compilationError;
  411. }
  412. /**
  413. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  414. * @param func The callback to be used.
  415. */
  416. public executeWhenCompiled(func: (effect: Effect) => void): void {
  417. if (this.isReady()) {
  418. func(this);
  419. return;
  420. }
  421. this.onCompileObservable.add((effect) => {
  422. func(effect);
  423. });
  424. if (!this._program || this._program.isParallelCompiled) {
  425. setTimeout(() => {
  426. this._checkIsReady();
  427. }, 16);
  428. }
  429. }
  430. private _checkIsReady() {
  431. if (this.isReady()) {
  432. return;
  433. }
  434. setTimeout(() => {
  435. this._checkIsReady();
  436. }, 16);
  437. }
  438. /** @hidden */
  439. public _loadVertexShader(vertex: any, callback: (data: any) => void): void {
  440. if (Tools.IsWindowObjectExist()) {
  441. // DOM element ?
  442. if (vertex instanceof HTMLElement) {
  443. var vertexCode = Tools.GetDOMTextContent(vertex);
  444. callback(vertexCode);
  445. return;
  446. }
  447. }
  448. // Base64 encoded ?
  449. if (vertex.substr(0, 7) === "base64:") {
  450. var vertexBinary = window.atob(vertex.substr(7));
  451. callback(vertexBinary);
  452. return;
  453. }
  454. // Is in local store ?
  455. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  456. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  457. return;
  458. }
  459. var vertexShaderUrl;
  460. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  461. vertexShaderUrl = vertex;
  462. } else {
  463. vertexShaderUrl = Engine.ShadersRepository + vertex;
  464. }
  465. // Vertex shader
  466. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  467. }
  468. /** @hidden */
  469. public _loadFragmentShader(fragment: any, callback: (data: any) => void): void {
  470. if (Tools.IsWindowObjectExist()) {
  471. // DOM element ?
  472. if (fragment instanceof HTMLElement) {
  473. var fragmentCode = Tools.GetDOMTextContent(fragment);
  474. callback(fragmentCode);
  475. return;
  476. }
  477. }
  478. // Base64 encoded ?
  479. if (fragment.substr(0, 7) === "base64:") {
  480. var fragmentBinary = window.atob(fragment.substr(7));
  481. callback(fragmentBinary);
  482. return;
  483. }
  484. // Is in local store ?
  485. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  486. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  487. return;
  488. }
  489. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  490. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  491. return;
  492. }
  493. var fragmentShaderUrl;
  494. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  495. fragmentShaderUrl = fragment;
  496. } else {
  497. fragmentShaderUrl = Engine.ShadersRepository + fragment;
  498. }
  499. // Fragment shader
  500. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  501. }
  502. /** @hidden */
  503. public _dumpShadersSource(vertexCode: string, fragmentCode: string, defines: string): void {
  504. // Rebuild shaders source code
  505. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  506. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  507. vertexCode = prefix + vertexCode;
  508. fragmentCode = prefix + fragmentCode;
  509. // Number lines of shaders source code
  510. var i = 2;
  511. var regex = /\n/gm;
  512. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function() { return "\n" + (i++) + "\t"; });
  513. i = 2;
  514. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function() { return "\n" + (i++) + "\t"; });
  515. // Dump shaders name and formatted source code
  516. if (this.name.vertexElement) {
  517. Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  518. Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  519. }
  520. else if (this.name.vertex) {
  521. Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  522. Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  523. }
  524. else {
  525. Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  526. Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  527. }
  528. }
  529. private _processShaderConversion(sourceCode: string, isFragment: boolean, callback: (data: any) => void): void {
  530. var preparedSourceCode = this._processPrecision(sourceCode);
  531. if (this._engine.webGLVersion == 1) {
  532. callback(preparedSourceCode);
  533. return;
  534. }
  535. // Already converted
  536. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  537. callback(preparedSourceCode.replace("#version 300 es", ""));
  538. return;
  539. }
  540. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  541. // Remove extensions
  542. // #extension GL_OES_standard_derivatives : enable
  543. // #extension GL_EXT_shader_texture_lod : enable
  544. // #extension GL_EXT_frag_depth : enable
  545. // #extension GL_EXT_draw_buffers : require
  546. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  547. var result = preparedSourceCode.replace(regex, "");
  548. // Migrate to GLSL v300
  549. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  550. result = result.replace(/attribute[ \t]/g, "in ");
  551. result = result.replace(/[ \t]attribute/g, " in");
  552. result = result.replace(/texture2D\s*\(/g, "texture(");
  553. if (isFragment) {
  554. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  555. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  556. result = result.replace(/textureCube\s*\(/g, "texture(");
  557. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  558. result = result.replace(/gl_FragColor/g, "glFragColor");
  559. result = result.replace(/gl_FragData/g, "glFragData");
  560. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  561. }
  562. callback(result);
  563. }
  564. private _processIncludes(sourceCode: string, callback: (data: any) => void): void {
  565. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  566. var match = regex.exec(sourceCode);
  567. var returnValue = new String(sourceCode);
  568. while (match != null) {
  569. var includeFile = match[1];
  570. // Uniform declaration
  571. if (includeFile.indexOf("__decl__") !== -1) {
  572. includeFile = includeFile.replace(/__decl__/, "");
  573. if (this._engine.supportsUniformBuffers) {
  574. includeFile = includeFile.replace(/Vertex/, "Ubo");
  575. includeFile = includeFile.replace(/Fragment/, "Ubo");
  576. }
  577. includeFile = includeFile + "Declaration";
  578. }
  579. if (Effect.IncludesShadersStore[includeFile]) {
  580. // Substitution
  581. var includeContent = Effect.IncludesShadersStore[includeFile];
  582. if (match[2]) {
  583. var splits = match[3].split(",");
  584. for (var index = 0; index < splits.length; index += 2) {
  585. var source = new RegExp(splits[index], "g");
  586. var dest = splits[index + 1];
  587. includeContent = includeContent.replace(source, dest);
  588. }
  589. }
  590. if (match[4]) {
  591. var indexString = match[5];
  592. if (indexString.indexOf("..") !== -1) {
  593. var indexSplits = indexString.split("..");
  594. var minIndex = parseInt(indexSplits[0]);
  595. var maxIndex = parseInt(indexSplits[1]);
  596. var sourceIncludeContent = includeContent.slice(0);
  597. includeContent = "";
  598. if (isNaN(maxIndex)) {
  599. maxIndex = this._indexParameters[indexSplits[1]];
  600. }
  601. for (var i = minIndex; i < maxIndex; i++) {
  602. if (!this._engine.supportsUniformBuffers) {
  603. // Ubo replacement
  604. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, (str: string, p1: string) => {
  605. return p1 + "{X}";
  606. });
  607. }
  608. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  609. }
  610. } else {
  611. if (!this._engine.supportsUniformBuffers) {
  612. // Ubo replacement
  613. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, (str: string, p1: string) => {
  614. return p1 + "{X}";
  615. });
  616. }
  617. includeContent = includeContent.replace(/\{X\}/g, indexString);
  618. }
  619. }
  620. // Replace
  621. returnValue = returnValue.replace(match[0], includeContent);
  622. } else {
  623. var includeShaderUrl = Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  624. this._engine._loadFile(includeShaderUrl, (fileContent) => {
  625. Effect.IncludesShadersStore[includeFile] = fileContent as string;
  626. this._processIncludes(<string>returnValue, callback);
  627. });
  628. return;
  629. }
  630. match = regex.exec(sourceCode);
  631. }
  632. callback(returnValue);
  633. }
  634. private _processPrecision(source: string): string {
  635. if (source.indexOf("precision highp float") === -1) {
  636. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  637. source = "precision mediump float;\n" + source;
  638. } else {
  639. source = "precision highp float;\n" + source;
  640. }
  641. } else {
  642. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  643. source = source.replace("precision highp float", "precision mediump float");
  644. }
  645. }
  646. return source;
  647. }
  648. /**
  649. * Recompiles the webGL program
  650. * @param vertexSourceCode The source code for the vertex shader.
  651. * @param fragmentSourceCode The source code for the fragment shader.
  652. * @param onCompiled Callback called when completed.
  653. * @param onError Callback called on error.
  654. * @hidden
  655. */
  656. public _rebuildProgram(vertexSourceCode: string, fragmentSourceCode: string, onCompiled: (program: WebGLProgram) => void, onError: (message: string) => void) {
  657. this._isReady = false;
  658. this._vertexSourceCodeOverride = vertexSourceCode;
  659. this._fragmentSourceCodeOverride = fragmentSourceCode;
  660. this.onError = (effect, error) => {
  661. if (onError) {
  662. onError(error);
  663. }
  664. };
  665. this.onCompiled = () => {
  666. var scenes = this.getEngine().scenes;
  667. for (var i = 0; i < scenes.length; i++) {
  668. scenes[i].markAllMaterialsAsDirty(Material.TextureDirtyFlag);
  669. }
  670. if (onCompiled) {
  671. onCompiled(this._program);
  672. }
  673. };
  674. this._fallbacks = null;
  675. this._prepareEffect();
  676. }
  677. /**
  678. * Gets the uniform locations of the the specified variable names
  679. * @param names THe names of the variables to lookup.
  680. * @returns Array of locations in the same order as variable names.
  681. */
  682. public getSpecificUniformLocations(names: string[]): Nullable<WebGLUniformLocation>[] {
  683. let engine = this._engine;
  684. return engine.getUniforms(this._program, names);
  685. }
  686. /**
  687. * Prepares the effect
  688. * @hidden
  689. */
  690. public _prepareEffect() {
  691. let attributesNames = this._attributesNames;
  692. let defines = this.defines;
  693. let fallbacks = this._fallbacks;
  694. this._valueCache = {};
  695. var previousProgram = this._program;
  696. try {
  697. let engine = this._engine;
  698. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  699. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  700. }
  701. else {
  702. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  703. }
  704. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  705. engine._executeWhenProgramIsCompiled(this._program, () => {
  706. if (engine.supportsUniformBuffers) {
  707. for (var name in this._uniformBuffersNames) {
  708. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  709. }
  710. }
  711. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  712. this._attributes = engine.getAttributes(this._program, attributesNames);
  713. var index: number;
  714. for (index = 0; index < this._samplers.length; index++) {
  715. var sampler = this.getUniform(this._samplers[index]);
  716. if (sampler == null) {
  717. this._samplers.splice(index, 1);
  718. index--;
  719. }
  720. }
  721. engine.bindSamplers(this);
  722. this._compilationError = "";
  723. this._isReady = true;
  724. if (this.onCompiled) {
  725. this.onCompiled(this);
  726. }
  727. this.onCompileObservable.notifyObservers(this);
  728. this.onCompileObservable.clear();
  729. // Unbind mesh reference in fallbacks
  730. if (this._fallbacks) {
  731. this._fallbacks.unBindMesh();
  732. }
  733. if (previousProgram) {
  734. this.getEngine()._deleteProgram(previousProgram);
  735. }
  736. });
  737. if (this._program.isParallelCompiled) {
  738. this._checkIsReady();
  739. }
  740. } catch (e) {
  741. this._compilationError = e.message;
  742. // Let's go through fallbacks then
  743. Tools.Error("Unable to compile effect:");
  744. Tools.Error("Uniforms: " + this._uniformsNames.map(function(uniform) {
  745. return " " + uniform;
  746. }));
  747. Tools.Error("Attributes: " + attributesNames.map(function(attribute) {
  748. return " " + attribute;
  749. }));
  750. Tools.Error("Error: " + this._compilationError);
  751. if (previousProgram) {
  752. this._program = previousProgram;
  753. this._isReady = true;
  754. if (this.onError) {
  755. this.onError(this, this._compilationError);
  756. }
  757. this.onErrorObservable.notifyObservers(this);
  758. }
  759. if (fallbacks && fallbacks.isMoreFallbacks) {
  760. Tools.Error("Trying next fallback.");
  761. this.defines = fallbacks.reduce(this.defines, this);
  762. this._prepareEffect();
  763. } else { // Sorry we did everything we can
  764. if (this.onError) {
  765. this.onError(this, this._compilationError);
  766. }
  767. this.onErrorObservable.notifyObservers(this);
  768. this.onErrorObservable.clear();
  769. // Unbind mesh reference in fallbacks
  770. if (this._fallbacks) {
  771. this._fallbacks.unBindMesh();
  772. }
  773. }
  774. }
  775. }
  776. /**
  777. * Checks if the effect is supported. (Must be called after compilation)
  778. */
  779. public get isSupported(): boolean {
  780. return this._compilationError === "";
  781. }
  782. /**
  783. * Binds a texture to the engine to be used as output of the shader.
  784. * @param channel Name of the output variable.
  785. * @param texture Texture to bind.
  786. * @hidden
  787. */
  788. public _bindTexture(channel: string, texture: InternalTexture): void {
  789. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  790. }
  791. /**
  792. * Sets a texture on the engine to be used in the shader.
  793. * @param channel Name of the sampler variable.
  794. * @param texture Texture to set.
  795. */
  796. public setTexture(channel: string, texture: Nullable<BaseTexture>): void {
  797. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  798. }
  799. /**
  800. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  801. * @param channel Name of the sampler variable.
  802. * @param texture Texture to set.
  803. */
  804. public setDepthStencilTexture(channel: string, texture: Nullable<RenderTargetTexture>): void {
  805. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  806. }
  807. /**
  808. * Sets an array of textures on the engine to be used in the shader.
  809. * @param channel Name of the variable.
  810. * @param textures Textures to set.
  811. */
  812. public setTextureArray(channel: string, textures: BaseTexture[]): void {
  813. if (this._samplers.indexOf(channel + "Ex") === -1) {
  814. var initialPos = this._samplers.indexOf(channel);
  815. for (var index = 1; index < textures.length; index++) {
  816. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  817. }
  818. }
  819. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  820. }
  821. /**
  822. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  823. * @param channel Name of the sampler variable.
  824. * @param postProcess Post process to get the input texture from.
  825. */
  826. public setTextureFromPostProcess(channel: string, postProcess: Nullable<PostProcess>): void {
  827. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  828. }
  829. /**
  830. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  831. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  832. * @param channel Name of the sampler variable.
  833. * @param postProcess Post process to get the output texture from.
  834. */
  835. public setTextureFromPostProcessOutput(channel: string, postProcess: Nullable<PostProcess>): void {
  836. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  837. }
  838. /** @hidden */
  839. public _cacheMatrix(uniformName: string, matrix: Matrix): boolean {
  840. var cache = this._valueCache[uniformName];
  841. var flag = matrix.updateFlag;
  842. if (cache !== undefined && cache === flag) {
  843. return false;
  844. }
  845. this._valueCache[uniformName] = flag;
  846. return true;
  847. }
  848. /** @hidden */
  849. public _cacheFloat2(uniformName: string, x: number, y: number): boolean {
  850. var cache = this._valueCache[uniformName];
  851. if (!cache) {
  852. cache = [x, y];
  853. this._valueCache[uniformName] = cache;
  854. return true;
  855. }
  856. var changed = false;
  857. if (cache[0] !== x) {
  858. cache[0] = x;
  859. changed = true;
  860. }
  861. if (cache[1] !== y) {
  862. cache[1] = y;
  863. changed = true;
  864. }
  865. return changed;
  866. }
  867. /** @hidden */
  868. public _cacheFloat3(uniformName: string, x: number, y: number, z: number): boolean {
  869. var cache = this._valueCache[uniformName];
  870. if (!cache) {
  871. cache = [x, y, z];
  872. this._valueCache[uniformName] = cache;
  873. return true;
  874. }
  875. var changed = false;
  876. if (cache[0] !== x) {
  877. cache[0] = x;
  878. changed = true;
  879. }
  880. if (cache[1] !== y) {
  881. cache[1] = y;
  882. changed = true;
  883. }
  884. if (cache[2] !== z) {
  885. cache[2] = z;
  886. changed = true;
  887. }
  888. return changed;
  889. }
  890. /** @hidden */
  891. public _cacheFloat4(uniformName: string, x: number, y: number, z: number, w: number): boolean {
  892. var cache = this._valueCache[uniformName];
  893. if (!cache) {
  894. cache = [x, y, z, w];
  895. this._valueCache[uniformName] = cache;
  896. return true;
  897. }
  898. var changed = false;
  899. if (cache[0] !== x) {
  900. cache[0] = x;
  901. changed = true;
  902. }
  903. if (cache[1] !== y) {
  904. cache[1] = y;
  905. changed = true;
  906. }
  907. if (cache[2] !== z) {
  908. cache[2] = z;
  909. changed = true;
  910. }
  911. if (cache[3] !== w) {
  912. cache[3] = w;
  913. changed = true;
  914. }
  915. return changed;
  916. }
  917. /**
  918. * Binds a buffer to a uniform.
  919. * @param buffer Buffer to bind.
  920. * @param name Name of the uniform variable to bind to.
  921. */
  922. public bindUniformBuffer(buffer: WebGLBuffer, name: string): void {
  923. let bufferName = this._uniformBuffersNames[name];
  924. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  925. return;
  926. }
  927. Effect._baseCache[bufferName] = buffer;
  928. this._engine.bindUniformBufferBase(buffer, bufferName);
  929. }
  930. /**
  931. * Binds block to a uniform.
  932. * @param blockName Name of the block to bind.
  933. * @param index Index to bind.
  934. */
  935. public bindUniformBlock(blockName: string, index: number): void {
  936. this._engine.bindUniformBlock(this._program, blockName, index);
  937. }
  938. /**
  939. * Sets an interger value on a uniform variable.
  940. * @param uniformName Name of the variable.
  941. * @param value Value to be set.
  942. * @returns this effect.
  943. */
  944. public setInt(uniformName: string, value: number): Effect {
  945. var cache = this._valueCache[uniformName];
  946. if (cache !== undefined && cache === value) {
  947. return this;
  948. }
  949. this._valueCache[uniformName] = value;
  950. this._engine.setInt(this.getUniform(uniformName), value);
  951. return this;
  952. }
  953. /**
  954. * Sets an int array on a uniform variable.
  955. * @param uniformName Name of the variable.
  956. * @param array array to be set.
  957. * @returns this effect.
  958. */
  959. public setIntArray(uniformName: string, array: Int32Array): Effect {
  960. this._valueCache[uniformName] = null;
  961. this._engine.setIntArray(this.getUniform(uniformName), array);
  962. return this;
  963. }
  964. /**
  965. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  966. * @param uniformName Name of the variable.
  967. * @param array array to be set.
  968. * @returns this effect.
  969. */
  970. public setIntArray2(uniformName: string, array: Int32Array): Effect {
  971. this._valueCache[uniformName] = null;
  972. this._engine.setIntArray2(this.getUniform(uniformName), array);
  973. return this;
  974. }
  975. /**
  976. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  977. * @param uniformName Name of the variable.
  978. * @param array array to be set.
  979. * @returns this effect.
  980. */
  981. public setIntArray3(uniformName: string, array: Int32Array): Effect {
  982. this._valueCache[uniformName] = null;
  983. this._engine.setIntArray3(this.getUniform(uniformName), array);
  984. return this;
  985. }
  986. /**
  987. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  988. * @param uniformName Name of the variable.
  989. * @param array array to be set.
  990. * @returns this effect.
  991. */
  992. public setIntArray4(uniformName: string, array: Int32Array): Effect {
  993. this._valueCache[uniformName] = null;
  994. this._engine.setIntArray4(this.getUniform(uniformName), array);
  995. return this;
  996. }
  997. /**
  998. * Sets an float array on a uniform variable.
  999. * @param uniformName Name of the variable.
  1000. * @param array array to be set.
  1001. * @returns this effect.
  1002. */
  1003. public setFloatArray(uniformName: string, array: Float32Array): Effect {
  1004. this._valueCache[uniformName] = null;
  1005. this._engine.setFloatArray(this.getUniform(uniformName), array);
  1006. return this;
  1007. }
  1008. /**
  1009. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  1010. * @param uniformName Name of the variable.
  1011. * @param array array to be set.
  1012. * @returns this effect.
  1013. */
  1014. public setFloatArray2(uniformName: string, array: Float32Array): Effect {
  1015. this._valueCache[uniformName] = null;
  1016. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  1017. return this;
  1018. }
  1019. /**
  1020. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1021. * @param uniformName Name of the variable.
  1022. * @param array array to be set.
  1023. * @returns this effect.
  1024. */
  1025. public setFloatArray3(uniformName: string, array: Float32Array): Effect {
  1026. this._valueCache[uniformName] = null;
  1027. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  1028. return this;
  1029. }
  1030. /**
  1031. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1032. * @param uniformName Name of the variable.
  1033. * @param array array to be set.
  1034. * @returns this effect.
  1035. */
  1036. public setFloatArray4(uniformName: string, array: Float32Array): Effect {
  1037. this._valueCache[uniformName] = null;
  1038. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  1039. return this;
  1040. }
  1041. /**
  1042. * Sets an array on a uniform variable.
  1043. * @param uniformName Name of the variable.
  1044. * @param array array to be set.
  1045. * @returns this effect.
  1046. */
  1047. public setArray(uniformName: string, array: number[]): Effect {
  1048. this._valueCache[uniformName] = null;
  1049. this._engine.setArray(this.getUniform(uniformName), array);
  1050. return this;
  1051. }
  1052. /**
  1053. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  1054. * @param uniformName Name of the variable.
  1055. * @param array array to be set.
  1056. * @returns this effect.
  1057. */
  1058. public setArray2(uniformName: string, array: number[]): Effect {
  1059. this._valueCache[uniformName] = null;
  1060. this._engine.setArray2(this.getUniform(uniformName), array);
  1061. return this;
  1062. }
  1063. /**
  1064. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1065. * @param uniformName Name of the variable.
  1066. * @param array array to be set.
  1067. * @returns this effect.
  1068. */
  1069. public setArray3(uniformName: string, array: number[]): Effect {
  1070. this._valueCache[uniformName] = null;
  1071. this._engine.setArray3(this.getUniform(uniformName), array);
  1072. return this;
  1073. }
  1074. /**
  1075. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1076. * @param uniformName Name of the variable.
  1077. * @param array array to be set.
  1078. * @returns this effect.
  1079. */
  1080. public setArray4(uniformName: string, array: number[]): Effect {
  1081. this._valueCache[uniformName] = null;
  1082. this._engine.setArray4(this.getUniform(uniformName), array);
  1083. return this;
  1084. }
  1085. /**
  1086. * Sets matrices on a uniform variable.
  1087. * @param uniformName Name of the variable.
  1088. * @param matrices matrices to be set.
  1089. * @returns this effect.
  1090. */
  1091. public setMatrices(uniformName: string, matrices: Float32Array): Effect {
  1092. if (!matrices) {
  1093. return this;
  1094. }
  1095. this._valueCache[uniformName] = null;
  1096. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1097. return this;
  1098. }
  1099. /**
  1100. * Sets matrix on a uniform variable.
  1101. * @param uniformName Name of the variable.
  1102. * @param matrix matrix to be set.
  1103. * @returns this effect.
  1104. */
  1105. public setMatrix(uniformName: string, matrix: Matrix): Effect {
  1106. if (this._cacheMatrix(uniformName, matrix)) {
  1107. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1108. }
  1109. return this;
  1110. }
  1111. /**
  1112. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1113. * @param uniformName Name of the variable.
  1114. * @param matrix matrix to be set.
  1115. * @returns this effect.
  1116. */
  1117. public setMatrix3x3(uniformName: string, matrix: Float32Array): Effect {
  1118. this._valueCache[uniformName] = null;
  1119. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1120. return this;
  1121. }
  1122. /**
  1123. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1124. * @param uniformName Name of the variable.
  1125. * @param matrix matrix to be set.
  1126. * @returns this effect.
  1127. */
  1128. public setMatrix2x2(uniformName: string, matrix: Float32Array): Effect {
  1129. this._valueCache[uniformName] = null;
  1130. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1131. return this;
  1132. }
  1133. /**
  1134. * Sets a float on a uniform variable.
  1135. * @param uniformName Name of the variable.
  1136. * @param value value to be set.
  1137. * @returns this effect.
  1138. */
  1139. public setFloat(uniformName: string, value: number): Effect {
  1140. var cache = this._valueCache[uniformName];
  1141. if (cache !== undefined && cache === value) {
  1142. return this;
  1143. }
  1144. this._valueCache[uniformName] = value;
  1145. this._engine.setFloat(this.getUniform(uniformName), value);
  1146. return this;
  1147. }
  1148. /**
  1149. * Sets a boolean on a uniform variable.
  1150. * @param uniformName Name of the variable.
  1151. * @param bool value to be set.
  1152. * @returns this effect.
  1153. */
  1154. public setBool(uniformName: string, bool: boolean): Effect {
  1155. var cache = this._valueCache[uniformName];
  1156. if (cache !== undefined && cache === bool) {
  1157. return this;
  1158. }
  1159. this._valueCache[uniformName] = bool;
  1160. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1161. return this;
  1162. }
  1163. /**
  1164. * Sets a Vector2 on a uniform variable.
  1165. * @param uniformName Name of the variable.
  1166. * @param vector2 vector2 to be set.
  1167. * @returns this effect.
  1168. */
  1169. public setVector2(uniformName: string, vector2: Vector2): Effect {
  1170. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1171. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1172. }
  1173. return this;
  1174. }
  1175. /**
  1176. * Sets a float2 on a uniform variable.
  1177. * @param uniformName Name of the variable.
  1178. * @param x First float in float2.
  1179. * @param y Second float in float2.
  1180. * @returns this effect.
  1181. */
  1182. public setFloat2(uniformName: string, x: number, y: number): Effect {
  1183. if (this._cacheFloat2(uniformName, x, y)) {
  1184. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1185. }
  1186. return this;
  1187. }
  1188. /**
  1189. * Sets a Vector3 on a uniform variable.
  1190. * @param uniformName Name of the variable.
  1191. * @param vector3 Value to be set.
  1192. * @returns this effect.
  1193. */
  1194. public setVector3(uniformName: string, vector3: Vector3): Effect {
  1195. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1196. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1197. }
  1198. return this;
  1199. }
  1200. /**
  1201. * Sets a float3 on a uniform variable.
  1202. * @param uniformName Name of the variable.
  1203. * @param x First float in float3.
  1204. * @param y Second float in float3.
  1205. * @param z Third float in float3.
  1206. * @returns this effect.
  1207. */
  1208. public setFloat3(uniformName: string, x: number, y: number, z: number): Effect {
  1209. if (this._cacheFloat3(uniformName, x, y, z)) {
  1210. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1211. }
  1212. return this;
  1213. }
  1214. /**
  1215. * Sets a Vector4 on a uniform variable.
  1216. * @param uniformName Name of the variable.
  1217. * @param vector4 Value to be set.
  1218. * @returns this effect.
  1219. */
  1220. public setVector4(uniformName: string, vector4: Vector4): Effect {
  1221. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1222. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1223. }
  1224. return this;
  1225. }
  1226. /**
  1227. * Sets a float4 on a uniform variable.
  1228. * @param uniformName Name of the variable.
  1229. * @param x First float in float4.
  1230. * @param y Second float in float4.
  1231. * @param z Third float in float4.
  1232. * @param w Fourth float in float4.
  1233. * @returns this effect.
  1234. */
  1235. public setFloat4(uniformName: string, x: number, y: number, z: number, w: number): Effect {
  1236. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1237. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1238. }
  1239. return this;
  1240. }
  1241. /**
  1242. * Sets a Color3 on a uniform variable.
  1243. * @param uniformName Name of the variable.
  1244. * @param color3 Value to be set.
  1245. * @returns this effect.
  1246. */
  1247. public setColor3(uniformName: string, color3: Color3): Effect {
  1248. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1249. this._engine.setColor3(this.getUniform(uniformName), color3);
  1250. }
  1251. return this;
  1252. }
  1253. /**
  1254. * Sets a Color4 on a uniform variable.
  1255. * @param uniformName Name of the variable.
  1256. * @param color3 Value to be set.
  1257. * @param alpha Alpha value to be set.
  1258. * @returns this effect.
  1259. */
  1260. public setColor4(uniformName: string, color3: Color3, alpha: number): Effect {
  1261. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1262. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1263. }
  1264. return this;
  1265. }
  1266. /**
  1267. * Sets a Color4 on a uniform variable
  1268. * @param uniformName defines the name of the variable
  1269. * @param color4 defines the value to be set
  1270. * @returns this effect.
  1271. */
  1272. public setDirectColor4(uniformName: string, color4: Color4): Effect {
  1273. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1274. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1275. }
  1276. return this;
  1277. }
  1278. /**
  1279. * This function will add a new shader to the shader store
  1280. * @param name the name of the shader
  1281. * @param pixelShader optional pixel shader content
  1282. * @param vertexShader optional vertex shader content
  1283. */
  1284. public static RegisterShader(name: string, pixelShader?: string, vertexShader?: string) {
  1285. if (pixelShader) {
  1286. Effect.ShadersStore[`${name}PixelShader`] = pixelShader;
  1287. }
  1288. if (vertexShader) {
  1289. Effect.ShadersStore[`${name}VertexShader`] = vertexShader;
  1290. }
  1291. }
  1292. /**
  1293. * Store of each shader (The can be looked up using effect.key)
  1294. */
  1295. public static ShadersStore: { [key: string]: string } = {};
  1296. /**
  1297. * Store of each included file for a shader (The can be looked up using effect.key)
  1298. */
  1299. public static IncludesShadersStore: { [key: string]: string } = {};
  1300. /**
  1301. * Resets the cache of effects.
  1302. */
  1303. public static ResetCache() {
  1304. Effect._baseCache = {};
  1305. }
  1306. }