effect.ts 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286
  1. import { Observable } from "../Misc/observable";
  2. import { Nullable } from "../types";
  3. import { Constants } from "../Engines/constants";
  4. import { DomManagement } from "../Misc/domManagement";
  5. import { Logger } from "../Misc/logger";
  6. import { IDisposable } from '../scene';
  7. import { IPipelineContext } from '../Engines/IPipelineContext';
  8. import { DataBuffer } from '../Meshes/dataBuffer';
  9. import { ShaderProcessor } from '../Engines/Processors/shaderProcessor';
  10. import { IMatrixLike, IVector2Like, IVector3Like, IVector4Like, IColor3Like, IColor4Like } from '../Maths/math.like';
  11. import { ThinEngine } from '../Engines/thinEngine';
  12. import { IEffectFallbacks } from './iEffectFallbacks';
  13. declare type Engine = import("../Engines/engine").Engine;
  14. declare type InternalTexture = import("../Materials/Textures/internalTexture").InternalTexture;
  15. declare type BaseTexture = import("../Materials/Textures/baseTexture").BaseTexture;
  16. declare type RenderTargetTexture = import("../Materials/Textures/renderTargetTexture").RenderTargetTexture;
  17. declare type PostProcess = import("../PostProcesses/postProcess").PostProcess;
  18. /**
  19. * Options to be used when creating an effect.
  20. */
  21. export interface IEffectCreationOptions {
  22. /**
  23. * Atrributes that will be used in the shader.
  24. */
  25. attributes: string[];
  26. /**
  27. * Uniform varible names that will be set in the shader.
  28. */
  29. uniformsNames: string[];
  30. /**
  31. * Uniform buffer variable names that will be set in the shader.
  32. */
  33. uniformBuffersNames: string[];
  34. /**
  35. * Sampler texture variable names that will be set in the shader.
  36. */
  37. samplers: string[];
  38. /**
  39. * Define statements that will be set in the shader.
  40. */
  41. defines: any;
  42. /**
  43. * Possible fallbacks for this effect to improve performance when needed.
  44. */
  45. fallbacks: Nullable<IEffectFallbacks>;
  46. /**
  47. * Callback that will be called when the shader is compiled.
  48. */
  49. onCompiled: Nullable<(effect: Effect) => void>;
  50. /**
  51. * Callback that will be called if an error occurs during shader compilation.
  52. */
  53. onError: Nullable<(effect: Effect, errors: string) => void>;
  54. /**
  55. * Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  56. */
  57. indexParameters?: any;
  58. /**
  59. * Max number of lights that can be used in the shader.
  60. */
  61. maxSimultaneousLights?: number;
  62. /**
  63. * See https://developer.mozilla.org/en-US/docs/Web/API/WebGL2RenderingContext/transformFeedbackVaryings
  64. */
  65. transformFeedbackVaryings?: Nullable<string[]>;
  66. }
  67. /**
  68. * Effect containing vertex and fragment shader that can be executed on an object.
  69. */
  70. export class Effect implements IDisposable {
  71. /**
  72. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  73. */
  74. public static ShadersRepository = "src/Shaders/";
  75. /**
  76. * Name of the effect.
  77. */
  78. public name: any = null;
  79. /**
  80. * String container all the define statements that should be set on the shader.
  81. */
  82. public defines: string = "";
  83. /**
  84. * Callback that will be called when the shader is compiled.
  85. */
  86. public onCompiled: Nullable<(effect: Effect) => void> = null;
  87. /**
  88. * Callback that will be called if an error occurs during shader compilation.
  89. */
  90. public onError: Nullable<(effect: Effect, errors: string) => void> = null;
  91. /**
  92. * Callback that will be called when effect is bound.
  93. */
  94. public onBind: Nullable<(effect: Effect) => void> = null;
  95. /**
  96. * Unique ID of the effect.
  97. */
  98. public uniqueId = 0;
  99. /**
  100. * Observable that will be called when the shader is compiled.
  101. * It is recommended to use executeWhenCompile() or to make sure that scene.isReady() is called to get this observable raised.
  102. */
  103. public onCompileObservable = new Observable<Effect>();
  104. /**
  105. * Observable that will be called if an error occurs during shader compilation.
  106. */
  107. public onErrorObservable = new Observable<Effect>();
  108. /** @hidden */
  109. public _onBindObservable: Nullable<Observable<Effect>> = null;
  110. /**
  111. * @hidden
  112. * Specifies if the effect was previously ready
  113. */
  114. public _wasPreviouslyReady = false;
  115. /**
  116. * Observable that will be called when effect is bound.
  117. */
  118. public get onBindObservable(): Observable<Effect> {
  119. if (!this._onBindObservable) {
  120. this._onBindObservable = new Observable<Effect>();
  121. }
  122. return this._onBindObservable;
  123. }
  124. /** @hidden */
  125. public _bonesComputationForcedToCPU = false;
  126. private static _uniqueIdSeed = 0;
  127. private _engine: Engine;
  128. private _uniformBuffersNames: { [key: string]: number } = {};
  129. private _uniformsNames: string[];
  130. private _samplerList: string[];
  131. private _samplers: { [key: string]: number } = {};
  132. private _isReady = false;
  133. private _compilationError = "";
  134. private _allFallbacksProcessed = false;
  135. private _attributesNames: string[];
  136. private _attributes: number[];
  137. private _attributeLocationByName: { [name: string] : number };
  138. private _uniforms: { [key: string]: Nullable<WebGLUniformLocation> } = {};
  139. /**
  140. * Key for the effect.
  141. * @hidden
  142. */
  143. public _key: string = "";
  144. private _indexParameters: any;
  145. private _fallbacks: Nullable<IEffectFallbacks> = null;
  146. private _vertexSourceCode: string = "";
  147. private _fragmentSourceCode: string = "";
  148. private _vertexSourceCodeOverride: string = "";
  149. private _fragmentSourceCodeOverride: string = "";
  150. private _transformFeedbackVaryings: Nullable<string[]> = null;
  151. /**
  152. * Compiled shader to webGL program.
  153. * @hidden
  154. */
  155. public _pipelineContext: Nullable<IPipelineContext> = null;
  156. private _valueCache: { [key: string]: any } = {};
  157. private static _baseCache: { [key: number]: DataBuffer } = {};
  158. /**
  159. * Instantiates an effect.
  160. * An effect can be used to create/manage/execute vertex and fragment shaders.
  161. * @param baseName Name of the effect.
  162. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  163. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  164. * @param samplers List of sampler variables that will be passed to the shader.
  165. * @param engine Engine to be used to render the effect
  166. * @param defines Define statements to be added to the shader.
  167. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  168. * @param onCompiled Callback that will be called when the shader is compiled.
  169. * @param onError Callback that will be called if an error occurs during shader compilation.
  170. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  171. */
  172. constructor(baseName: any, attributesNamesOrOptions: string[] | IEffectCreationOptions, uniformsNamesOrEngine: string[] | ThinEngine, samplers: Nullable<string[]> = null,
  173. engine?: ThinEngine, defines: Nullable<string> = null,
  174. fallbacks: Nullable<IEffectFallbacks> = null, onCompiled: Nullable<(effect: Effect) => void> = null, onError: Nullable<(effect: Effect, errors: string) => void> = null, indexParameters?: any) {
  175. this.name = baseName;
  176. if ((<IEffectCreationOptions>attributesNamesOrOptions).attributes) {
  177. var options = <IEffectCreationOptions>attributesNamesOrOptions;
  178. this._engine = <Engine>uniformsNamesOrEngine;
  179. this._attributesNames = options.attributes;
  180. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  181. this._samplerList = options.samplers.slice();
  182. this.defines = options.defines;
  183. this.onError = options.onError;
  184. this.onCompiled = options.onCompiled;
  185. this._fallbacks = options.fallbacks;
  186. this._indexParameters = options.indexParameters;
  187. this._transformFeedbackVaryings = options.transformFeedbackVaryings || null;
  188. if (options.uniformBuffersNames) {
  189. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  190. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  191. }
  192. }
  193. } else {
  194. this._engine = <Engine>engine;
  195. this.defines = (defines == null ? "" : defines);
  196. this._uniformsNames = (<string[]>uniformsNamesOrEngine).concat(<string[]>samplers);
  197. this._samplerList = samplers ? <string[]>samplers.slice() : [];
  198. this._attributesNames = (<string[]>attributesNamesOrOptions);
  199. this.onError = onError;
  200. this.onCompiled = onCompiled;
  201. this._indexParameters = indexParameters;
  202. this._fallbacks = fallbacks;
  203. }
  204. this._attributeLocationByName = { };
  205. this.uniqueId = Effect._uniqueIdSeed++;
  206. var vertexSource: any;
  207. var fragmentSource: any;
  208. let hostDocument = DomManagement.IsWindowObjectExist() ? this._engine.getHostDocument() : null;
  209. if (baseName.vertexSource) {
  210. vertexSource = "source:" + baseName.vertexSource;
  211. } else if (baseName.vertexElement) {
  212. vertexSource = hostDocument ? hostDocument.getElementById(baseName.vertexElement) : null;
  213. if (!vertexSource) {
  214. vertexSource = baseName.vertexElement;
  215. }
  216. } else {
  217. vertexSource = baseName.vertex || baseName;
  218. }
  219. if (baseName.fragmentSource) {
  220. fragmentSource = "source:" + baseName.fragmentSource;
  221. } else if (baseName.fragmentElement) {
  222. fragmentSource = hostDocument ? hostDocument.getElementById(baseName.fragmentElement) : null;
  223. if (!fragmentSource) {
  224. fragmentSource = baseName.fragmentElement;
  225. }
  226. } else {
  227. fragmentSource = baseName.fragment || baseName;
  228. }
  229. let processorOptions = {
  230. defines: this.defines.split("\n"),
  231. indexParameters: this._indexParameters,
  232. isFragment: false,
  233. shouldUseHighPrecisionShader: this._engine._shouldUseHighPrecisionShader,
  234. processor: this._engine._shaderProcessor,
  235. supportsUniformBuffers: this._engine.supportsUniformBuffers,
  236. shadersRepository: Effect.ShadersRepository,
  237. includesShadersStore: Effect.IncludesShadersStore,
  238. version: (this._engine.webGLVersion * 100).toString(),
  239. platformName: this._engine.webGLVersion >= 2 ? "WEBGL2" : "WEBGL1"
  240. };
  241. this._loadShader(vertexSource, "Vertex", "", (vertexCode) => {
  242. this._loadShader(fragmentSource, "Fragment", "Pixel", (fragmentCode) => {
  243. ShaderProcessor.Process(vertexCode, processorOptions, (migratedVertexCode) => {
  244. processorOptions.isFragment = true;
  245. ShaderProcessor.Process(fragmentCode, processorOptions, (migratedFragmentCode) => {
  246. this._useFinalCode(migratedVertexCode, migratedFragmentCode, baseName);
  247. });
  248. });
  249. });
  250. });
  251. }
  252. private _useFinalCode(migratedVertexCode: string, migratedFragmentCode: string, baseName: any) {
  253. if (baseName) {
  254. var vertex = baseName.vertexElement || baseName.vertex || baseName.spectorName || baseName;
  255. var fragment = baseName.fragmentElement || baseName.fragment || baseName.spectorName || baseName;
  256. this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  257. this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  258. } else {
  259. this._vertexSourceCode = migratedVertexCode;
  260. this._fragmentSourceCode = migratedFragmentCode;
  261. }
  262. this._prepareEffect();
  263. }
  264. /**
  265. * Unique key for this effect
  266. */
  267. public get key(): string {
  268. return this._key;
  269. }
  270. /**
  271. * If the effect has been compiled and prepared.
  272. * @returns if the effect is compiled and prepared.
  273. */
  274. public isReady(): boolean {
  275. try {
  276. return this._isReadyInternal();
  277. }
  278. catch {
  279. return false;
  280. }
  281. }
  282. private _isReadyInternal(): boolean {
  283. if (this._isReady) {
  284. return true;
  285. }
  286. if (this._pipelineContext) {
  287. return this._pipelineContext.isReady;
  288. }
  289. return false;
  290. }
  291. /**
  292. * The engine the effect was initialized with.
  293. * @returns the engine.
  294. */
  295. public getEngine(): Engine {
  296. return this._engine;
  297. }
  298. /**
  299. * The pipeline context for this effect
  300. * @returns the associated pipeline context
  301. */
  302. public getPipelineContext(): Nullable<IPipelineContext> {
  303. return this._pipelineContext;
  304. }
  305. /**
  306. * The set of names of attribute variables for the shader.
  307. * @returns An array of attribute names.
  308. */
  309. public getAttributesNames(): string[] {
  310. return this._attributesNames;
  311. }
  312. /**
  313. * Returns the attribute at the given index.
  314. * @param index The index of the attribute.
  315. * @returns The location of the attribute.
  316. */
  317. public getAttributeLocation(index: number): number {
  318. return this._attributes[index];
  319. }
  320. /**
  321. * Returns the attribute based on the name of the variable.
  322. * @param name of the attribute to look up.
  323. * @returns the attribute location.
  324. */
  325. public getAttributeLocationByName(name: string): number {
  326. return this._attributeLocationByName[name];
  327. }
  328. /**
  329. * The number of attributes.
  330. * @returns the numnber of attributes.
  331. */
  332. public getAttributesCount(): number {
  333. return this._attributes.length;
  334. }
  335. /**
  336. * Gets the index of a uniform variable.
  337. * @param uniformName of the uniform to look up.
  338. * @returns the index.
  339. */
  340. public getUniformIndex(uniformName: string): number {
  341. return this._uniformsNames.indexOf(uniformName);
  342. }
  343. /**
  344. * Returns the attribute based on the name of the variable.
  345. * @param uniformName of the uniform to look up.
  346. * @returns the location of the uniform.
  347. */
  348. public getUniform(uniformName: string): Nullable<WebGLUniformLocation> {
  349. return this._uniforms[uniformName];
  350. }
  351. /**
  352. * Returns an array of sampler variable names
  353. * @returns The array of sampler variable neames.
  354. */
  355. public getSamplers(): string[] {
  356. return this._samplerList;
  357. }
  358. /**
  359. * The error from the last compilation.
  360. * @returns the error string.
  361. */
  362. public getCompilationError(): string {
  363. return this._compilationError;
  364. }
  365. /**
  366. * Gets a boolean indicating that all fallbacks were used during compilation
  367. * @returns true if all fallbacks were used
  368. */
  369. public allFallbacksProcessed(): boolean {
  370. return this._allFallbacksProcessed;
  371. }
  372. /**
  373. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  374. * @param func The callback to be used.
  375. */
  376. public executeWhenCompiled(func: (effect: Effect) => void): void {
  377. if (this.isReady()) {
  378. func(this);
  379. return;
  380. }
  381. this.onCompileObservable.add((effect) => {
  382. func(effect);
  383. });
  384. if (!this._pipelineContext || this._pipelineContext.isAsync) {
  385. setTimeout(() => {
  386. this._checkIsReady(null);
  387. }, 16);
  388. }
  389. }
  390. private _checkIsReady(previousPipelineContext: Nullable<IPipelineContext>) {
  391. try {
  392. if (this._isReadyInternal()) {
  393. return;
  394. }
  395. } catch (e) {
  396. this._processCompilationErrors(e, previousPipelineContext);
  397. return;
  398. }
  399. setTimeout(() => {
  400. this._checkIsReady(previousPipelineContext);
  401. }, 16);
  402. }
  403. private _loadShader(shader: any, key: string, optionalKey: string, callback: (data: any) => void): void {
  404. if (typeof(HTMLElement) !== "undefined") {
  405. // DOM element ?
  406. if (shader instanceof HTMLElement) {
  407. var shaderCode = DomManagement.GetDOMTextContent(shader);
  408. callback(shaderCode);
  409. return;
  410. }
  411. }
  412. // Direct source ?
  413. if (shader.substr(0, 7) === "source:") {
  414. callback(shader.substr(7));
  415. return;
  416. }
  417. // Base64 encoded ?
  418. if (shader.substr(0, 7) === "base64:") {
  419. var shaderBinary = window.atob(shader.substr(7));
  420. callback(shaderBinary);
  421. return;
  422. }
  423. // Is in local store ?
  424. if (Effect.ShadersStore[shader + key + "Shader"]) {
  425. callback(Effect.ShadersStore[shader + key + "Shader"]);
  426. return;
  427. }
  428. if (optionalKey && Effect.ShadersStore[shader + optionalKey + "Shader"]) {
  429. callback(Effect.ShadersStore[shader + optionalKey + "Shader"]);
  430. return;
  431. }
  432. var shaderUrl;
  433. if (shader[0] === "." || shader[0] === "/" || shader.indexOf("http") > -1) {
  434. shaderUrl = shader;
  435. } else {
  436. shaderUrl = Effect.ShadersRepository + shader;
  437. }
  438. // Vertex shader
  439. this._engine._loadFile(shaderUrl + "." + key.toLowerCase() + ".fx", callback);
  440. }
  441. /**
  442. * Recompiles the webGL program
  443. * @param vertexSourceCode The source code for the vertex shader.
  444. * @param fragmentSourceCode The source code for the fragment shader.
  445. * @param onCompiled Callback called when completed.
  446. * @param onError Callback called on error.
  447. * @hidden
  448. */
  449. public _rebuildProgram(vertexSourceCode: string, fragmentSourceCode: string, onCompiled: (pipelineContext: IPipelineContext) => void, onError: (message: string) => void) {
  450. this._isReady = false;
  451. this._vertexSourceCodeOverride = vertexSourceCode;
  452. this._fragmentSourceCodeOverride = fragmentSourceCode;
  453. this.onError = (effect, error) => {
  454. if (onError) {
  455. onError(error);
  456. }
  457. };
  458. this.onCompiled = () => {
  459. var scenes = this.getEngine().scenes;
  460. if (scenes) {
  461. for (var i = 0; i < scenes.length; i++) {
  462. scenes[i].markAllMaterialsAsDirty(Constants.MATERIAL_AllDirtyFlag);
  463. }
  464. }
  465. this._pipelineContext!._handlesSpectorRebuildCallback(onCompiled);
  466. };
  467. this._fallbacks = null;
  468. this._prepareEffect();
  469. }
  470. /**
  471. * Prepares the effect
  472. * @hidden
  473. */
  474. public _prepareEffect() {
  475. let attributesNames = this._attributesNames;
  476. let defines = this.defines;
  477. this._valueCache = {};
  478. var previousPipelineContext = this._pipelineContext;
  479. try {
  480. let engine = this._engine;
  481. this._pipelineContext = engine.createPipelineContext();
  482. let rebuildRebind = this._rebuildProgram.bind(this);
  483. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  484. engine._preparePipelineContext(this._pipelineContext, this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, true, rebuildRebind, null, this._transformFeedbackVaryings);
  485. }
  486. else {
  487. engine._preparePipelineContext(this._pipelineContext, this._vertexSourceCode, this._fragmentSourceCode, false, rebuildRebind, defines, this._transformFeedbackVaryings);
  488. }
  489. engine._executeWhenRenderingStateIsCompiled(this._pipelineContext, () => {
  490. if (engine.supportsUniformBuffers) {
  491. for (var name in this._uniformBuffersNames) {
  492. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  493. }
  494. }
  495. let uniforms = engine.getUniforms(this._pipelineContext!, this._uniformsNames);
  496. uniforms.forEach((uniform, index) => {
  497. this._uniforms[this._uniformsNames[index]] = uniform;
  498. });
  499. this._attributes = engine.getAttributes(this._pipelineContext!, attributesNames);
  500. if (attributesNames) {
  501. for (let i = 0; i < attributesNames.length; i++) {
  502. const name = attributesNames[i];
  503. this._attributeLocationByName[name] = this._attributes[i];
  504. }
  505. }
  506. var index: number;
  507. for (index = 0; index < this._samplerList.length; index++) {
  508. var sampler = this.getUniform(this._samplerList[index]);
  509. if (sampler == null) {
  510. this._samplerList.splice(index, 1);
  511. index--;
  512. }
  513. }
  514. this._samplerList.forEach((name, index) => {
  515. this._samplers[name] = index;
  516. });
  517. engine.bindSamplers(this);
  518. this._compilationError = "";
  519. this._isReady = true;
  520. if (this.onCompiled) {
  521. this.onCompiled(this);
  522. }
  523. this.onCompileObservable.notifyObservers(this);
  524. this.onCompileObservable.clear();
  525. // Unbind mesh reference in fallbacks
  526. if (this._fallbacks) {
  527. this._fallbacks.unBindMesh();
  528. }
  529. if (previousPipelineContext) {
  530. this.getEngine()._deletePipelineContext(previousPipelineContext);
  531. }
  532. });
  533. if (this._pipelineContext.isAsync) {
  534. this._checkIsReady(previousPipelineContext);
  535. }
  536. } catch (e) {
  537. this._processCompilationErrors(e, previousPipelineContext);
  538. }
  539. }
  540. private _processCompilationErrors(e: any, previousPipelineContext: Nullable<IPipelineContext> = null) {
  541. this._compilationError = e.message;
  542. let attributesNames = this._attributesNames;
  543. let fallbacks = this._fallbacks;
  544. // Let's go through fallbacks then
  545. Logger.Error("Unable to compile effect:");
  546. Logger.Error("Uniforms: " + this._uniformsNames.map(function(uniform) {
  547. return " " + uniform;
  548. }));
  549. Logger.Error("Attributes: " + attributesNames.map(function(attribute) {
  550. return " " + attribute;
  551. }));
  552. Logger.Error("Defines:\r\n" + this.defines);
  553. Logger.Error("Error: " + this._compilationError);
  554. if (previousPipelineContext) {
  555. this._pipelineContext = previousPipelineContext;
  556. this._isReady = true;
  557. if (this.onError) {
  558. this.onError(this, this._compilationError);
  559. }
  560. this.onErrorObservable.notifyObservers(this);
  561. }
  562. if (fallbacks) {
  563. this._pipelineContext = null;
  564. if (fallbacks.hasMoreFallbacks) {
  565. this._allFallbacksProcessed = false;
  566. Logger.Error("Trying next fallback.");
  567. this.defines = fallbacks.reduce(this.defines, this);
  568. this._prepareEffect();
  569. } else { // Sorry we did everything we can
  570. this._allFallbacksProcessed = true;
  571. if (this.onError) {
  572. this.onError(this, this._compilationError);
  573. }
  574. this.onErrorObservable.notifyObservers(this);
  575. this.onErrorObservable.clear();
  576. // Unbind mesh reference in fallbacks
  577. if (this._fallbacks) {
  578. this._fallbacks.unBindMesh();
  579. }
  580. }
  581. } else {
  582. this._allFallbacksProcessed = true;
  583. }
  584. }
  585. /**
  586. * Checks if the effect is supported. (Must be called after compilation)
  587. */
  588. public get isSupported(): boolean {
  589. return this._compilationError === "";
  590. }
  591. /**
  592. * Binds a texture to the engine to be used as output of the shader.
  593. * @param channel Name of the output variable.
  594. * @param texture Texture to bind.
  595. * @hidden
  596. */
  597. public _bindTexture(channel: string, texture: Nullable<InternalTexture>): void {
  598. this._engine._bindTexture(this._samplers[channel], texture);
  599. }
  600. /**
  601. * Sets a texture on the engine to be used in the shader.
  602. * @param channel Name of the sampler variable.
  603. * @param texture Texture to set.
  604. */
  605. public setTexture(channel: string, texture: Nullable<BaseTexture>): void {
  606. this._engine.setTexture(this._samplers[channel], this._uniforms[channel], texture);
  607. }
  608. /**
  609. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  610. * @param channel Name of the sampler variable.
  611. * @param texture Texture to set.
  612. */
  613. public setDepthStencilTexture(channel: string, texture: Nullable<RenderTargetTexture>): void {
  614. this._engine.setDepthStencilTexture(this._samplers[channel], this._uniforms[channel], texture);
  615. }
  616. /**
  617. * Sets an array of textures on the engine to be used in the shader.
  618. * @param channel Name of the variable.
  619. * @param textures Textures to set.
  620. */
  621. public setTextureArray(channel: string, textures: BaseTexture[]): void {
  622. let exName = channel + "Ex";
  623. if (this._samplerList.indexOf(exName + "0") === -1) {
  624. const initialPos = this._samplerList.indexOf(channel);
  625. for (var index = 1; index < textures.length; index++) {
  626. const currentExName = exName + (index - 1).toString();
  627. this._samplerList.splice(initialPos + index, 0, currentExName);
  628. }
  629. // Reset every channels
  630. let channelIndex = 0;
  631. for (var key of this._samplerList) {
  632. this._samplers[key] = channelIndex;
  633. channelIndex += 1;
  634. }
  635. }
  636. this._engine.setTextureArray(this._samplers[channel], this._uniforms[channel], textures);
  637. }
  638. /**
  639. * 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)
  640. * @param channel Name of the sampler variable.
  641. * @param postProcess Post process to get the input texture from.
  642. */
  643. public setTextureFromPostProcess(channel: string, postProcess: Nullable<PostProcess>): void {
  644. this._engine.setTextureFromPostProcess(this._samplers[channel], postProcess);
  645. }
  646. /**
  647. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  648. * 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)
  649. * @param channel Name of the sampler variable.
  650. * @param postProcess Post process to get the output texture from.
  651. */
  652. public setTextureFromPostProcessOutput(channel: string, postProcess: Nullable<PostProcess>): void {
  653. this._engine.setTextureFromPostProcessOutput(this._samplers[channel], postProcess);
  654. }
  655. /** @hidden */
  656. public _cacheMatrix(uniformName: string, matrix: IMatrixLike): boolean {
  657. var cache = this._valueCache[uniformName];
  658. var flag = matrix.updateFlag;
  659. if (cache !== undefined && cache === flag) {
  660. return false;
  661. }
  662. this._valueCache[uniformName] = flag;
  663. return true;
  664. }
  665. /** @hidden */
  666. public _cacheFloat2(uniformName: string, x: number, y: number): boolean {
  667. var cache = this._valueCache[uniformName];
  668. if (!cache || cache.length !== 2) {
  669. cache = [x, y];
  670. this._valueCache[uniformName] = cache;
  671. return true;
  672. }
  673. var changed = false;
  674. if (cache[0] !== x) {
  675. cache[0] = x;
  676. changed = true;
  677. }
  678. if (cache[1] !== y) {
  679. cache[1] = y;
  680. changed = true;
  681. }
  682. return changed;
  683. }
  684. /** @hidden */
  685. public _cacheFloat3(uniformName: string, x: number, y: number, z: number): boolean {
  686. var cache = this._valueCache[uniformName];
  687. if (!cache || cache.length !== 3) {
  688. cache = [x, y, z];
  689. this._valueCache[uniformName] = cache;
  690. return true;
  691. }
  692. var changed = false;
  693. if (cache[0] !== x) {
  694. cache[0] = x;
  695. changed = true;
  696. }
  697. if (cache[1] !== y) {
  698. cache[1] = y;
  699. changed = true;
  700. }
  701. if (cache[2] !== z) {
  702. cache[2] = z;
  703. changed = true;
  704. }
  705. return changed;
  706. }
  707. /** @hidden */
  708. public _cacheFloat4(uniformName: string, x: number, y: number, z: number, w: number): boolean {
  709. var cache = this._valueCache[uniformName];
  710. if (!cache || cache.length !== 4) {
  711. cache = [x, y, z, w];
  712. this._valueCache[uniformName] = cache;
  713. return true;
  714. }
  715. var changed = false;
  716. if (cache[0] !== x) {
  717. cache[0] = x;
  718. changed = true;
  719. }
  720. if (cache[1] !== y) {
  721. cache[1] = y;
  722. changed = true;
  723. }
  724. if (cache[2] !== z) {
  725. cache[2] = z;
  726. changed = true;
  727. }
  728. if (cache[3] !== w) {
  729. cache[3] = w;
  730. changed = true;
  731. }
  732. return changed;
  733. }
  734. /**
  735. * Binds a buffer to a uniform.
  736. * @param buffer Buffer to bind.
  737. * @param name Name of the uniform variable to bind to.
  738. */
  739. public bindUniformBuffer(buffer: DataBuffer, name: string): void {
  740. let bufferName = this._uniformBuffersNames[name];
  741. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  742. return;
  743. }
  744. Effect._baseCache[bufferName] = buffer;
  745. this._engine.bindUniformBufferBase(buffer, bufferName);
  746. }
  747. /**
  748. * Binds block to a uniform.
  749. * @param blockName Name of the block to bind.
  750. * @param index Index to bind.
  751. */
  752. public bindUniformBlock(blockName: string, index: number): void {
  753. this._engine.bindUniformBlock(this._pipelineContext!, blockName, index);
  754. }
  755. /**
  756. * Sets an interger value on a uniform variable.
  757. * @param uniformName Name of the variable.
  758. * @param value Value to be set.
  759. * @returns this effect.
  760. */
  761. public setInt(uniformName: string, value: number): Effect {
  762. var cache = this._valueCache[uniformName];
  763. if (cache !== undefined && cache === value) {
  764. return this;
  765. }
  766. this._valueCache[uniformName] = value;
  767. this._engine.setInt(this._uniforms[uniformName], value);
  768. return this;
  769. }
  770. /**
  771. * Sets an int array on a uniform variable.
  772. * @param uniformName Name of the variable.
  773. * @param array array to be set.
  774. * @returns this effect.
  775. */
  776. public setIntArray(uniformName: string, array: Int32Array): Effect {
  777. this._valueCache[uniformName] = null;
  778. this._engine.setIntArray(this._uniforms[uniformName], array);
  779. return this;
  780. }
  781. /**
  782. * 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)
  783. * @param uniformName Name of the variable.
  784. * @param array array to be set.
  785. * @returns this effect.
  786. */
  787. public setIntArray2(uniformName: string, array: Int32Array): Effect {
  788. this._valueCache[uniformName] = null;
  789. this._engine.setIntArray2(this._uniforms[uniformName], array);
  790. return this;
  791. }
  792. /**
  793. * 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)
  794. * @param uniformName Name of the variable.
  795. * @param array array to be set.
  796. * @returns this effect.
  797. */
  798. public setIntArray3(uniformName: string, array: Int32Array): Effect {
  799. this._valueCache[uniformName] = null;
  800. this._engine.setIntArray3(this._uniforms[uniformName], array);
  801. return this;
  802. }
  803. /**
  804. * 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)
  805. * @param uniformName Name of the variable.
  806. * @param array array to be set.
  807. * @returns this effect.
  808. */
  809. public setIntArray4(uniformName: string, array: Int32Array): Effect {
  810. this._valueCache[uniformName] = null;
  811. this._engine.setIntArray4(this._uniforms[uniformName], array);
  812. return this;
  813. }
  814. /**
  815. * Sets an float array on a uniform variable.
  816. * @param uniformName Name of the variable.
  817. * @param array array to be set.
  818. * @returns this effect.
  819. */
  820. public setFloatArray(uniformName: string, array: Float32Array): Effect {
  821. this._valueCache[uniformName] = null;
  822. this._engine.setArray(this._uniforms[uniformName], array);
  823. return this;
  824. }
  825. /**
  826. * 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)
  827. * @param uniformName Name of the variable.
  828. * @param array array to be set.
  829. * @returns this effect.
  830. */
  831. public setFloatArray2(uniformName: string, array: Float32Array): Effect {
  832. this._valueCache[uniformName] = null;
  833. this._engine.setArray2(this._uniforms[uniformName], array);
  834. return this;
  835. }
  836. /**
  837. * 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)
  838. * @param uniformName Name of the variable.
  839. * @param array array to be set.
  840. * @returns this effect.
  841. */
  842. public setFloatArray3(uniformName: string, array: Float32Array): Effect {
  843. this._valueCache[uniformName] = null;
  844. this._engine.setArray3(this._uniforms[uniformName], array);
  845. return this;
  846. }
  847. /**
  848. * 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)
  849. * @param uniformName Name of the variable.
  850. * @param array array to be set.
  851. * @returns this effect.
  852. */
  853. public setFloatArray4(uniformName: string, array: Float32Array): Effect {
  854. this._valueCache[uniformName] = null;
  855. this._engine.setArray4(this._uniforms[uniformName], array);
  856. return this;
  857. }
  858. /**
  859. * Sets an array on a uniform variable.
  860. * @param uniformName Name of the variable.
  861. * @param array array to be set.
  862. * @returns this effect.
  863. */
  864. public setArray(uniformName: string, array: number[]): Effect {
  865. this._valueCache[uniformName] = null;
  866. this._engine.setArray(this._uniforms[uniformName], array);
  867. return this;
  868. }
  869. /**
  870. * 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)
  871. * @param uniformName Name of the variable.
  872. * @param array array to be set.
  873. * @returns this effect.
  874. */
  875. public setArray2(uniformName: string, array: number[]): Effect {
  876. this._valueCache[uniformName] = null;
  877. this._engine.setArray2(this._uniforms[uniformName], array);
  878. return this;
  879. }
  880. /**
  881. * 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)
  882. * @param uniformName Name of the variable.
  883. * @param array array to be set.
  884. * @returns this effect.
  885. */
  886. public setArray3(uniformName: string, array: number[]): Effect {
  887. this._valueCache[uniformName] = null;
  888. this._engine.setArray3(this._uniforms[uniformName], array);
  889. return this;
  890. }
  891. /**
  892. * 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)
  893. * @param uniformName Name of the variable.
  894. * @param array array to be set.
  895. * @returns this effect.
  896. */
  897. public setArray4(uniformName: string, array: number[]): Effect {
  898. this._valueCache[uniformName] = null;
  899. this._engine.setArray4(this._uniforms[uniformName], array);
  900. return this;
  901. }
  902. /**
  903. * Sets matrices on a uniform variable.
  904. * @param uniformName Name of the variable.
  905. * @param matrices matrices to be set.
  906. * @returns this effect.
  907. */
  908. public setMatrices(uniformName: string, matrices: Float32Array): Effect {
  909. if (!matrices) {
  910. return this;
  911. }
  912. this._valueCache[uniformName] = null;
  913. this._engine.setMatrices(this._uniforms[uniformName], matrices);
  914. return this;
  915. }
  916. /**
  917. * Sets matrix on a uniform variable.
  918. * @param uniformName Name of the variable.
  919. * @param matrix matrix to be set.
  920. * @returns this effect.
  921. */
  922. public setMatrix(uniformName: string, matrix: IMatrixLike): Effect {
  923. if (this._cacheMatrix(uniformName, matrix)) {
  924. this._engine.setMatrices(this._uniforms[uniformName], matrix.toArray() as Float32Array);
  925. }
  926. return this;
  927. }
  928. /**
  929. * 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)
  930. * @param uniformName Name of the variable.
  931. * @param matrix matrix to be set.
  932. * @returns this effect.
  933. */
  934. public setMatrix3x3(uniformName: string, matrix: Float32Array): Effect {
  935. this._valueCache[uniformName] = null;
  936. this._engine.setMatrix3x3(this._uniforms[uniformName], matrix);
  937. return this;
  938. }
  939. /**
  940. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  941. * @param uniformName Name of the variable.
  942. * @param matrix matrix to be set.
  943. * @returns this effect.
  944. */
  945. public setMatrix2x2(uniformName: string, matrix: Float32Array): Effect {
  946. this._valueCache[uniformName] = null;
  947. this._engine.setMatrix2x2(this._uniforms[uniformName], matrix);
  948. return this;
  949. }
  950. /**
  951. * Sets a float on a uniform variable.
  952. * @param uniformName Name of the variable.
  953. * @param value value to be set.
  954. * @returns this effect.
  955. */
  956. public setFloat(uniformName: string, value: number): Effect {
  957. var cache = this._valueCache[uniformName];
  958. if (cache !== undefined && cache === value) {
  959. return this;
  960. }
  961. this._valueCache[uniformName] = value;
  962. this._engine.setFloat(this._uniforms[uniformName], value);
  963. return this;
  964. }
  965. /**
  966. * Sets a boolean on a uniform variable.
  967. * @param uniformName Name of the variable.
  968. * @param bool value to be set.
  969. * @returns this effect.
  970. */
  971. public setBool(uniformName: string, bool: boolean): Effect {
  972. var cache = this._valueCache[uniformName];
  973. if (cache !== undefined && cache === bool) {
  974. return this;
  975. }
  976. this._valueCache[uniformName] = bool;
  977. this._engine.setInt(this._uniforms[uniformName], bool ? 1 : 0);
  978. return this;
  979. }
  980. /**
  981. * Sets a Vector2 on a uniform variable.
  982. * @param uniformName Name of the variable.
  983. * @param vector2 vector2 to be set.
  984. * @returns this effect.
  985. */
  986. public setVector2(uniformName: string, vector2: IVector2Like): Effect {
  987. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  988. this._engine.setFloat2(this._uniforms[uniformName], vector2.x, vector2.y);
  989. }
  990. return this;
  991. }
  992. /**
  993. * Sets a float2 on a uniform variable.
  994. * @param uniformName Name of the variable.
  995. * @param x First float in float2.
  996. * @param y Second float in float2.
  997. * @returns this effect.
  998. */
  999. public setFloat2(uniformName: string, x: number, y: number): Effect {
  1000. if (this._cacheFloat2(uniformName, x, y)) {
  1001. this._engine.setFloat2(this._uniforms[uniformName], x, y);
  1002. }
  1003. return this;
  1004. }
  1005. /**
  1006. * Sets a Vector3 on a uniform variable.
  1007. * @param uniformName Name of the variable.
  1008. * @param vector3 Value to be set.
  1009. * @returns this effect.
  1010. */
  1011. public setVector3(uniformName: string, vector3: IVector3Like): Effect {
  1012. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1013. this._engine.setFloat3(this._uniforms[uniformName], vector3.x, vector3.y, vector3.z);
  1014. }
  1015. return this;
  1016. }
  1017. /**
  1018. * Sets a float3 on a uniform variable.
  1019. * @param uniformName Name of the variable.
  1020. * @param x First float in float3.
  1021. * @param y Second float in float3.
  1022. * @param z Third float in float3.
  1023. * @returns this effect.
  1024. */
  1025. public setFloat3(uniformName: string, x: number, y: number, z: number): Effect {
  1026. if (this._cacheFloat3(uniformName, x, y, z)) {
  1027. this._engine.setFloat3(this._uniforms[uniformName], x, y, z);
  1028. }
  1029. return this;
  1030. }
  1031. /**
  1032. * Sets a Vector4 on a uniform variable.
  1033. * @param uniformName Name of the variable.
  1034. * @param vector4 Value to be set.
  1035. * @returns this effect.
  1036. */
  1037. public setVector4(uniformName: string, vector4: IVector4Like): Effect {
  1038. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1039. this._engine.setFloat4(this._uniforms[uniformName], vector4.x, vector4.y, vector4.z, vector4.w);
  1040. }
  1041. return this;
  1042. }
  1043. /**
  1044. * Sets a float4 on a uniform variable.
  1045. * @param uniformName Name of the variable.
  1046. * @param x First float in float4.
  1047. * @param y Second float in float4.
  1048. * @param z Third float in float4.
  1049. * @param w Fourth float in float4.
  1050. * @returns this effect.
  1051. */
  1052. public setFloat4(uniformName: string, x: number, y: number, z: number, w: number): Effect {
  1053. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1054. this._engine.setFloat4(this._uniforms[uniformName], x, y, z, w);
  1055. }
  1056. return this;
  1057. }
  1058. /**
  1059. * Sets a Color3 on a uniform variable.
  1060. * @param uniformName Name of the variable.
  1061. * @param color3 Value to be set.
  1062. * @returns this effect.
  1063. */
  1064. public setColor3(uniformName: string, color3: IColor3Like): Effect {
  1065. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1066. this._engine.setFloat3(this._uniforms[uniformName], color3.r, color3.g, color3.b);
  1067. }
  1068. return this;
  1069. }
  1070. /**
  1071. * Sets a Color4 on a uniform variable.
  1072. * @param uniformName Name of the variable.
  1073. * @param color3 Value to be set.
  1074. * @param alpha Alpha value to be set.
  1075. * @returns this effect.
  1076. */
  1077. public setColor4(uniformName: string, color3: IColor3Like, alpha: number): Effect {
  1078. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1079. this._engine.setFloat4(this._uniforms[uniformName], color3.r, color3.g, color3.b, alpha);
  1080. }
  1081. return this;
  1082. }
  1083. /**
  1084. * Sets a Color4 on a uniform variable
  1085. * @param uniformName defines the name of the variable
  1086. * @param color4 defines the value to be set
  1087. * @returns this effect.
  1088. */
  1089. public setDirectColor4(uniformName: string, color4: IColor4Like): Effect {
  1090. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1091. this._engine.setFloat4(this._uniforms[uniformName], color4.r, color4.g, color4.b, color4.a);
  1092. }
  1093. return this;
  1094. }
  1095. /** Release all associated resources */
  1096. public dispose() {
  1097. this._engine._releaseEffect(this);
  1098. }
  1099. /**
  1100. * This function will add a new shader to the shader store
  1101. * @param name the name of the shader
  1102. * @param pixelShader optional pixel shader content
  1103. * @param vertexShader optional vertex shader content
  1104. */
  1105. public static RegisterShader(name: string, pixelShader?: string, vertexShader?: string) {
  1106. if (pixelShader) {
  1107. Effect.ShadersStore[`${name}PixelShader`] = pixelShader;
  1108. }
  1109. if (vertexShader) {
  1110. Effect.ShadersStore[`${name}VertexShader`] = vertexShader;
  1111. }
  1112. }
  1113. /**
  1114. * Store of each shader (The can be looked up using effect.key)
  1115. */
  1116. public static ShadersStore: { [key: string]: string } = {};
  1117. /**
  1118. * Store of each included file for a shader (The can be looked up using effect.key)
  1119. */
  1120. public static IncludesShadersStore: { [key: string]: string } = {};
  1121. /**
  1122. * Resets the cache of effects.
  1123. */
  1124. public static ResetCache() {
  1125. Effect._baseCache = {};
  1126. }
  1127. }