babylon.effect.ts 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923
  1. module BABYLON {
  2. export class EffectFallbacks {
  3. private _defines = {};
  4. private _currentRank = 32;
  5. private _maxRank = -1;
  6. private _mesh: AbstractMesh;
  7. private _meshRank: number;
  8. public unBindMesh() {
  9. this._mesh = null;
  10. }
  11. public addFallback(rank: number, define: string): void {
  12. if (!this._defines[rank]) {
  13. if (rank < this._currentRank) {
  14. this._currentRank = rank;
  15. }
  16. if (rank > this._maxRank) {
  17. this._maxRank = rank;
  18. }
  19. this._defines[rank] = new Array<String>();
  20. }
  21. this._defines[rank].push(define);
  22. }
  23. public addCPUSkinningFallback(rank: number, mesh: BABYLON.AbstractMesh) {
  24. this._meshRank = rank;
  25. this._mesh = mesh;
  26. if (rank < this._currentRank) {
  27. this._currentRank = rank;
  28. }
  29. if (rank > this._maxRank) {
  30. this._maxRank = rank;
  31. }
  32. }
  33. public get isMoreFallbacks(): boolean {
  34. return this._currentRank <= this._maxRank;
  35. }
  36. public reduce(currentDefines: string): string {
  37. // First we try to switch to CPU skinning
  38. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  39. this._mesh.computeBonesUsingShaders = false;
  40. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  41. Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  42. var scene = this._mesh.getScene();
  43. for (var index = 0; index < scene.meshes.length; index++) {
  44. var otherMesh = scene.meshes[index];
  45. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  46. otherMesh.computeBonesUsingShaders = false;
  47. }
  48. }
  49. }
  50. else {
  51. var currentFallbacks = this._defines[this._currentRank];
  52. if (currentFallbacks) {
  53. for (var index = 0; index < currentFallbacks.length; index++) {
  54. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  55. }
  56. }
  57. this._currentRank++;
  58. }
  59. return currentDefines;
  60. }
  61. }
  62. export class EffectCreationOptions {
  63. public attributes: string[];
  64. public uniformsNames: string[];
  65. public uniformBuffersNames: string[];
  66. public samplers: string[];
  67. public defines: any;
  68. public fallbacks: EffectFallbacks;
  69. public onCompiled: (effect: Effect) => void;
  70. public onError: (effect: Effect, errors: string) => void;
  71. public indexParameters: any;
  72. public maxSimultaneousLights: number;
  73. }
  74. export class Effect {
  75. public name: any;
  76. public defines: string;
  77. public onCompiled: (effect: Effect) => void;
  78. public onError: (effect: Effect, errors: string) => void;
  79. public onBind: (effect: Effect) => void;
  80. public uniqueId = 0;
  81. public onCompileObservable = new Observable<Effect>();
  82. public onErrorObservable = new Observable<Effect>();
  83. public onBindObservable = new Observable<Effect>();
  84. private static _uniqueIdSeed = 0;
  85. private _engine: Engine;
  86. private _uniformBuffersNames: { [key: string]: number } = {};
  87. private _uniformsNames: string[];
  88. private _samplers: string[];
  89. private _isReady = false;
  90. private _compilationError = "";
  91. private _attributesNames: string[];
  92. private _attributes: number[];
  93. private _uniforms: WebGLUniformLocation[];
  94. public _key: string;
  95. private _indexParameters: any;
  96. private _fallbacks: EffectFallbacks;
  97. private _vertexSourceCode: string;
  98. private _fragmentSourceCode: string;
  99. private _program: WebGLProgram;
  100. private _valueCache: { [key: string]: any };
  101. private static _baseCache: { [key: number]: WebGLBuffer } = {};
  102. constructor(baseName: any, attributesNamesOrOptions: string[] | EffectCreationOptions, uniformsNamesOrEngine: string[] | Engine, samplers?: string[], engine?: Engine, defines?: string, fallbacks?: EffectFallbacks, onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void, indexParameters?: any) {
  103. this.name = baseName;
  104. if ((<EffectCreationOptions>attributesNamesOrOptions).attributes) {
  105. var options = <EffectCreationOptions>attributesNamesOrOptions;
  106. this._engine = <Engine>uniformsNamesOrEngine;
  107. this._attributesNames = options.attributes;
  108. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  109. this._samplers = options.samplers;
  110. this.defines = options.defines;
  111. this.onError = options.onError;
  112. this.onCompiled = options.onCompiled;
  113. this._fallbacks = options.fallbacks;
  114. this._indexParameters = options.indexParameters;
  115. if (options.uniformBuffersNames) {
  116. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  117. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  118. }
  119. }
  120. } else {
  121. this._engine = engine;
  122. this.defines = defines;
  123. this._uniformsNames = (<string[]>uniformsNamesOrEngine).concat(samplers);
  124. this._samplers = samplers;
  125. this._attributesNames = (<string[]>attributesNamesOrOptions);
  126. this.onError = onError;
  127. this.onCompiled = onCompiled;
  128. this._indexParameters = indexParameters;
  129. this._fallbacks = fallbacks;
  130. }
  131. this.uniqueId = Effect._uniqueIdSeed++;
  132. var vertexSource;
  133. var fragmentSource;
  134. if (baseName.vertexElement) {
  135. vertexSource = document.getElementById(baseName.vertexElement);
  136. if (!vertexSource) {
  137. vertexSource = baseName.vertexElement;
  138. }
  139. } else {
  140. vertexSource = baseName.vertex || baseName;
  141. }
  142. if (baseName.fragmentElement) {
  143. fragmentSource = document.getElementById(baseName.fragmentElement);
  144. if (!fragmentSource) {
  145. fragmentSource = baseName.fragmentElement;
  146. }
  147. } else {
  148. fragmentSource = baseName.fragment || baseName;
  149. }
  150. this._loadVertexShader(vertexSource, vertexCode => {
  151. this._processIncludes(vertexCode, vertexCodeWithIncludes => {
  152. this._processShaderConversion(vertexCodeWithIncludes, false, migratedVertexCode => {
  153. this._loadFragmentShader(fragmentSource, (fragmentCode) => {
  154. this._processIncludes(fragmentCode, fragmentCodeWithIncludes => {
  155. this._processShaderConversion(fragmentCodeWithIncludes, true, migratedFragmentCode => {
  156. if (baseName) {
  157. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  158. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  159. this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  160. this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  161. } else {
  162. this._vertexSourceCode = migratedVertexCode;
  163. this._fragmentSourceCode = migratedFragmentCode;
  164. }
  165. this._prepareEffect();
  166. });
  167. });
  168. });
  169. });
  170. });
  171. });
  172. }
  173. public get key(): string {
  174. return this._key;
  175. }
  176. // Properties
  177. public isReady(): boolean {
  178. return this._isReady;
  179. }
  180. public getEngine(): Engine {
  181. return this._engine;
  182. }
  183. public getProgram(): WebGLProgram {
  184. return this._program;
  185. }
  186. public getAttributesNames(): string[] {
  187. return this._attributesNames;
  188. }
  189. public getAttributeLocation(index: number): number {
  190. return this._attributes[index];
  191. }
  192. public getAttributeLocationByName(name: string): number {
  193. var index = this._attributesNames.indexOf(name);
  194. return this._attributes[index];
  195. }
  196. public getAttributesCount(): number {
  197. return this._attributes.length;
  198. }
  199. public getUniformIndex(uniformName: string): number {
  200. return this._uniformsNames.indexOf(uniformName);
  201. }
  202. public getUniform(uniformName: string): WebGLUniformLocation {
  203. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  204. }
  205. public getSamplers(): string[] {
  206. return this._samplers;
  207. }
  208. public getCompilationError(): string {
  209. return this._compilationError;
  210. }
  211. // Methods
  212. public executeWhenCompiled(func: (effect: Effect) => void): void {
  213. if (this.isReady()) {
  214. func(this);
  215. return;
  216. }
  217. this.onCompileObservable.add((effect) => {
  218. func(effect);
  219. });
  220. }
  221. public _loadVertexShader(vertex: any, callback: (data: any) => void): void {
  222. // DOM element ?
  223. if (vertex instanceof HTMLElement) {
  224. var vertexCode = Tools.GetDOMTextContent(vertex);
  225. callback(vertexCode);
  226. return;
  227. }
  228. // Base64 encoded ?
  229. if (vertex.substr(0, 7) === "base64:") {
  230. var vertexBinary = window.atob(vertex.substr(7));
  231. callback(vertexBinary);
  232. return;
  233. }
  234. // Is in local store ?
  235. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  236. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  237. return;
  238. }
  239. var vertexShaderUrl;
  240. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  241. vertexShaderUrl = vertex;
  242. } else {
  243. vertexShaderUrl = Engine.ShadersRepository + vertex;
  244. }
  245. // Vertex shader
  246. Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  247. }
  248. public _loadFragmentShader(fragment: any, callback: (data: any) => void): void {
  249. // DOM element ?
  250. if (fragment instanceof HTMLElement) {
  251. var fragmentCode = Tools.GetDOMTextContent(fragment);
  252. callback(fragmentCode);
  253. return;
  254. }
  255. // Base64 encoded ?
  256. if (fragment.substr(0, 7) === "base64:") {
  257. var fragmentBinary = window.atob(fragment.substr(7));
  258. callback(fragmentBinary);
  259. return;
  260. }
  261. // Is in local store ?
  262. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  263. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  264. return;
  265. }
  266. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  267. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  268. return;
  269. }
  270. var fragmentShaderUrl;
  271. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  272. fragmentShaderUrl = fragment;
  273. } else {
  274. fragmentShaderUrl = Engine.ShadersRepository + fragment;
  275. }
  276. // Fragment shader
  277. Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  278. }
  279. private _dumpShadersSource(vertexCode: string, fragmentCode: string, defines: string): void {
  280. // Rebuild shaders source code
  281. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  282. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  283. vertexCode = prefix + vertexCode;
  284. fragmentCode = prefix + fragmentCode;
  285. // Number lines of shaders source code
  286. var i = 2;
  287. var regex = /\n/gm;
  288. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function() { return "\n" + (i++) + "\t"; });
  289. i = 2;
  290. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function() { return "\n" + (i++) + "\t"; });
  291. // Dump shaders name and formatted source code
  292. if (this.name.vertexElement) {
  293. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  294. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  295. }
  296. else if (this.name.vertex) {
  297. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  298. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  299. }
  300. else {
  301. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  302. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  303. }
  304. };
  305. private _processShaderConversion(sourceCode: string, isFragment: boolean, callback: (data: any) => void): void {
  306. var preparedSourceCode = this._processPrecision(sourceCode);
  307. if (this._engine.webGLVersion == 1) {
  308. callback(preparedSourceCode);
  309. return;
  310. }
  311. // Already converted
  312. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  313. callback(preparedSourceCode.replace("#version 300 es", ""));
  314. return;
  315. }
  316. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  317. // Remove extensions
  318. // #extension GL_OES_standard_derivatives : enable
  319. // #extension GL_EXT_shader_texture_lod : enable
  320. // #extension GL_EXT_frag_depth : enable
  321. // #extension GL_EXT_draw_buffers : require
  322. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  323. var result = preparedSourceCode.replace(regex, "");
  324. // Migrate to GLSL v300
  325. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  326. result = result.replace(/attribute[ \t]/g, "in ");
  327. result = result.replace(/[ \t]attribute/g, " in");
  328. if (isFragment) {
  329. result = result.replace(/texture2DLodEXT\(/g, "textureLod(");
  330. result = result.replace(/textureCubeLodEXT\(/g, "textureLod(");
  331. result = result.replace(/texture2D\(/g, "texture(");
  332. result = result.replace(/textureCube\(/g, "texture(");
  333. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  334. result = result.replace(/gl_FragColor/g, "glFragColor");
  335. result = result.replace(/gl_FragData/g, "glFragData");
  336. result = result.replace(/void\s+?main\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  337. }
  338. callback(result);
  339. }
  340. private _processIncludes(sourceCode: string, callback: (data: any) => void): void {
  341. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  342. var match = regex.exec(sourceCode);
  343. var returnValue = new String(sourceCode);
  344. while (match != null) {
  345. var includeFile = match[1];
  346. // Uniform declaration
  347. if (includeFile.indexOf("__decl__") !== -1) {
  348. includeFile = includeFile.replace(/__decl__/, "");
  349. if (this._engine.supportsUniformBuffers) {
  350. includeFile = includeFile.replace(/Vertex/, "Ubo");
  351. includeFile = includeFile.replace(/Fragment/, "Ubo");
  352. }
  353. includeFile = includeFile + "Declaration";
  354. }
  355. if (Effect.IncludesShadersStore[includeFile]) {
  356. // Substitution
  357. var includeContent = Effect.IncludesShadersStore[includeFile];
  358. if (match[2]) {
  359. var splits = match[3].split(",");
  360. for (var index = 0; index < splits.length; index += 2) {
  361. var source = new RegExp(splits[index], "g");
  362. var dest = splits[index + 1];
  363. includeContent = includeContent.replace(source, dest);
  364. }
  365. }
  366. if (match[4]) {
  367. var indexString = match[5];
  368. if (indexString.indexOf("..") !== -1) {
  369. var indexSplits = indexString.split("..");
  370. var minIndex = parseInt(indexSplits[0]);
  371. var maxIndex = parseInt(indexSplits[1]);
  372. var sourceIncludeContent = includeContent.slice(0);
  373. includeContent = "";
  374. if (isNaN(maxIndex)) {
  375. maxIndex = this._indexParameters[indexSplits[1]];
  376. }
  377. for (var i = minIndex; i < maxIndex; i++) {
  378. if (!this._engine.supportsUniformBuffers) {
  379. // Ubo replacement
  380. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, (str: string, p1: string) => {
  381. return p1 + "{X}";
  382. });
  383. }
  384. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  385. }
  386. } else {
  387. if (!this._engine.supportsUniformBuffers) {
  388. // Ubo replacement
  389. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, (str: string, p1: string) => {
  390. return p1 + "{X}";
  391. });
  392. }
  393. includeContent = includeContent.replace(/\{X\}/g, indexString);
  394. }
  395. }
  396. // Replace
  397. returnValue = returnValue.replace(match[0], includeContent);
  398. } else {
  399. var includeShaderUrl = Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  400. Tools.LoadFile(includeShaderUrl, (fileContent) => {
  401. Effect.IncludesShadersStore[includeFile] = fileContent;
  402. this._processIncludes(<string>returnValue, callback);
  403. });
  404. return;
  405. }
  406. match = regex.exec(sourceCode);
  407. }
  408. callback(returnValue);
  409. }
  410. private _processPrecision(source: string): string {
  411. if (source.indexOf("precision highp float") === -1) {
  412. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  413. source = "precision mediump float;\n" + source;
  414. } else {
  415. source = "precision highp float;\n" + source;
  416. }
  417. } else {
  418. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  419. source = source.replace("precision highp float", "precision mediump float");
  420. }
  421. }
  422. return source;
  423. }
  424. public _prepareEffect() {
  425. let attributesNames = this._attributesNames;
  426. let defines = this.defines;
  427. let fallbacks = this._fallbacks;
  428. this._valueCache = {};
  429. try {
  430. var engine = this._engine;
  431. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines);
  432. if (engine.webGLVersion > 1) {
  433. for (var name in this._uniformBuffersNames) {
  434. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  435. }
  436. }
  437. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  438. this._attributes = engine.getAttributes(this._program, attributesNames);
  439. var index: number;
  440. for (index = 0; index < this._samplers.length; index++) {
  441. var sampler = this.getUniform(this._samplers[index]);
  442. if (sampler == null) {
  443. this._samplers.splice(index, 1);
  444. index--;
  445. }
  446. }
  447. engine.bindSamplers(this);
  448. this._compilationError = "";
  449. this._isReady = true;
  450. if (this.onCompiled) {
  451. this.onCompiled(this);
  452. }
  453. this.onCompileObservable.notifyObservers(this);
  454. this.onCompileObservable.clear();
  455. // Unbind mesh reference in fallbacks
  456. if (this._fallbacks) {
  457. this._fallbacks.unBindMesh();
  458. }
  459. } catch (e) {
  460. this._compilationError = e.message;
  461. // Let's go through fallbacks then
  462. Tools.Error("Unable to compile effect:");
  463. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function(uniform) {
  464. return " " + uniform;
  465. }));
  466. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function(attribute) {
  467. return " " + attribute;
  468. }));
  469. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  470. Tools.Error("Error: " + this._compilationError);
  471. if (fallbacks && fallbacks.isMoreFallbacks) {
  472. Tools.Error("Trying next fallback.");
  473. this.defines = fallbacks.reduce(this.defines);
  474. this._prepareEffect();
  475. } else { // Sorry we did everything we can
  476. if (this.onError) {
  477. this.onError(this, this._compilationError);
  478. }
  479. this.onErrorObservable.notifyObservers(this);
  480. this.onErrorObservable.clear();
  481. // Unbind mesh reference in fallbacks
  482. if (this._fallbacks) {
  483. this._fallbacks.unBindMesh();
  484. }
  485. }
  486. }
  487. }
  488. public get isSupported(): boolean {
  489. return this._compilationError === "";
  490. }
  491. public _bindTexture(channel: string, texture: InternalTexture): void {
  492. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  493. }
  494. public setTexture(channel: string, texture: BaseTexture): void {
  495. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  496. }
  497. public setTextureArray(channel: string, textures: BaseTexture[]): void {
  498. if (this._samplers.indexOf(channel + "Ex") === -1) {
  499. var initialPos = this._samplers.indexOf(channel);
  500. for (var index = 1; index < textures.length; index++) {
  501. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  502. }
  503. }
  504. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  505. }
  506. public setTextureFromPostProcess(channel: string, postProcess: PostProcess): void {
  507. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  508. }
  509. public _cacheMatrix(uniformName: string, matrix: Matrix): boolean {
  510. var cache = this._valueCache[uniformName];
  511. var flag = matrix.updateFlag;
  512. if (cache !== undefined && cache === flag) {
  513. return false;
  514. }
  515. this._valueCache[uniformName] = flag;
  516. return true;
  517. }
  518. public _cacheFloat2(uniformName: string, x: number, y: number): boolean {
  519. var cache = this._valueCache[uniformName];
  520. if (!cache) {
  521. cache = [x, y];
  522. this._valueCache[uniformName] = cache;
  523. return true;
  524. }
  525. var changed = false;
  526. if (cache[0] !== x) {
  527. cache[0] = x;
  528. changed = true;
  529. }
  530. if (cache[1] !== y) {
  531. cache[1] = y;
  532. changed = true;
  533. }
  534. return changed;
  535. }
  536. public _cacheFloat3(uniformName: string, x: number, y: number, z: number): boolean {
  537. var cache = this._valueCache[uniformName];
  538. if (!cache) {
  539. cache = [x, y, z];
  540. this._valueCache[uniformName] = cache;
  541. return true;
  542. }
  543. var changed = false;
  544. if (cache[0] !== x) {
  545. cache[0] = x;
  546. changed = true;
  547. }
  548. if (cache[1] !== y) {
  549. cache[1] = y;
  550. changed = true;
  551. }
  552. if (cache[2] !== z) {
  553. cache[2] = z;
  554. changed = true;
  555. }
  556. return changed;
  557. }
  558. public _cacheFloat4(uniformName: string, x: number, y: number, z: number, w: number): boolean {
  559. var cache = this._valueCache[uniformName];
  560. if (!cache) {
  561. cache = [x, y, z, w];
  562. this._valueCache[uniformName] = cache;
  563. return true;
  564. }
  565. var changed = false;
  566. if (cache[0] !== x) {
  567. cache[0] = x;
  568. changed = true;
  569. }
  570. if (cache[1] !== y) {
  571. cache[1] = y;
  572. changed = true;
  573. }
  574. if (cache[2] !== z) {
  575. cache[2] = z;
  576. changed = true;
  577. }
  578. if (cache[3] !== w) {
  579. cache[3] = w;
  580. changed = true;
  581. }
  582. return changed;
  583. }
  584. public bindUniformBuffer(buffer: WebGLBuffer, name: string): void {
  585. if (Effect._baseCache[this._uniformBuffersNames[name]] === buffer) {
  586. return;
  587. }
  588. Effect._baseCache[this._uniformBuffersNames[name]] = buffer;
  589. this._engine.bindUniformBufferBase(buffer, this._uniformBuffersNames[name]);
  590. }
  591. public bindUniformBlock(blockName: string, index: number): void {
  592. this._engine.bindUniformBlock(this._program, blockName, index);
  593. }
  594. public setIntArray(uniformName: string, array: Int32Array): Effect {
  595. this._valueCache[uniformName] = null;
  596. this._engine.setIntArray(this.getUniform(uniformName), array);
  597. return this;
  598. }
  599. public setIntArray2(uniformName: string, array: Int32Array): Effect {
  600. this._valueCache[uniformName] = null;
  601. this._engine.setIntArray2(this.getUniform(uniformName), array);
  602. return this;
  603. }
  604. public setIntArray3(uniformName: string, array: Int32Array): Effect {
  605. this._valueCache[uniformName] = null;
  606. this._engine.setIntArray3(this.getUniform(uniformName), array);
  607. return this;
  608. }
  609. public setIntArray4(uniformName: string, array: Int32Array): Effect {
  610. this._valueCache[uniformName] = null;
  611. this._engine.setIntArray4(this.getUniform(uniformName), array);
  612. return this;
  613. }
  614. public setFloatArray(uniformName: string, array: Float32Array): Effect {
  615. this._valueCache[uniformName] = null;
  616. this._engine.setFloatArray(this.getUniform(uniformName), array);
  617. return this;
  618. }
  619. public setFloatArray2(uniformName: string, array: Float32Array): Effect {
  620. this._valueCache[uniformName] = null;
  621. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  622. return this;
  623. }
  624. public setFloatArray3(uniformName: string, array: Float32Array): Effect {
  625. this._valueCache[uniformName] = null;
  626. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  627. return this;
  628. }
  629. public setFloatArray4(uniformName: string, array: Float32Array): Effect {
  630. this._valueCache[uniformName] = null;
  631. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  632. return this;
  633. }
  634. public setArray(uniformName: string, array: number[]): Effect {
  635. this._valueCache[uniformName] = null;
  636. this._engine.setArray(this.getUniform(uniformName), array);
  637. return this;
  638. }
  639. public setArray2(uniformName: string, array: number[]): Effect {
  640. this._valueCache[uniformName] = null;
  641. this._engine.setArray2(this.getUniform(uniformName), array);
  642. return this;
  643. }
  644. public setArray3(uniformName: string, array: number[]): Effect {
  645. this._valueCache[uniformName] = null;
  646. this._engine.setArray3(this.getUniform(uniformName), array);
  647. return this;
  648. }
  649. public setArray4(uniformName: string, array: number[]): Effect {
  650. this._valueCache[uniformName] = null;
  651. this._engine.setArray4(this.getUniform(uniformName), array);
  652. return this;
  653. }
  654. public setMatrices(uniformName: string, matrices: Float32Array): Effect {
  655. if (!matrices) {
  656. return;
  657. }
  658. this._valueCache[uniformName] = null;
  659. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  660. return this;
  661. }
  662. public setMatrix(uniformName: string, matrix: Matrix): Effect {
  663. if (this._cacheMatrix(uniformName, matrix)) {
  664. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  665. }
  666. return this;
  667. }
  668. public setMatrix3x3(uniformName: string, matrix: Float32Array): Effect {
  669. this._valueCache[uniformName] = null;
  670. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  671. return this;
  672. }
  673. public setMatrix2x2(uniformName: string, matrix: Float32Array): Effect {
  674. this._valueCache[uniformName] = null;
  675. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  676. return this;
  677. }
  678. public setFloat(uniformName: string, value: number): Effect {
  679. var cache = this._valueCache[uniformName];
  680. if (cache !== undefined && cache === value)
  681. return this;
  682. this._valueCache[uniformName] = value;
  683. this._engine.setFloat(this.getUniform(uniformName), value);
  684. return this;
  685. }
  686. public setBool(uniformName: string, bool: boolean): Effect {
  687. var cache = this._valueCache[uniformName];
  688. if (cache !== undefined && cache === bool)
  689. return this;
  690. this._valueCache[uniformName] = bool;
  691. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  692. return this;
  693. }
  694. public setVector2(uniformName: string, vector2: Vector2): Effect {
  695. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  696. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  697. }
  698. return this;
  699. }
  700. public setFloat2(uniformName: string, x: number, y: number): Effect {
  701. if (this._cacheFloat2(uniformName, x, y)) {
  702. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  703. }
  704. return this;
  705. }
  706. public setVector3(uniformName: string, vector3: Vector3): Effect {
  707. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  708. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  709. }
  710. return this;
  711. }
  712. public setFloat3(uniformName: string, x: number, y: number, z: number): Effect {
  713. if (this._cacheFloat3(uniformName, x, y, z)) {
  714. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  715. }
  716. return this;
  717. }
  718. public setVector4(uniformName: string, vector4: Vector4): Effect {
  719. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  720. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  721. }
  722. return this;
  723. }
  724. public setFloat4(uniformName: string, x: number, y: number, z: number, w: number): Effect {
  725. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  726. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  727. }
  728. return this;
  729. }
  730. public setColor3(uniformName: string, color3: Color3): Effect {
  731. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  732. this._engine.setColor3(this.getUniform(uniformName), color3);
  733. }
  734. return this;
  735. }
  736. public setColor4(uniformName: string, color3: Color3, alpha: number): Effect {
  737. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  738. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  739. }
  740. return this;
  741. }
  742. // Statics
  743. public static ShadersStore = {};
  744. public static IncludesShadersStore = {};
  745. public static ResetCache() {
  746. Effect._baseCache = {};
  747. }
  748. }
  749. }