shaderProcessor.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. import { ShaderCodeNode } from './shaderCodeNode';
  2. import { ShaderCodeCursor } from './shaderCodeCursor';
  3. import { ShaderCodeConditionNode } from './shaderCodeConditionNode';
  4. import { ShaderCodeTestNode } from './shaderCodeTestNode';
  5. import { ShaderDefineIsDefinedOperator } from './Expressions/Operators/shaderDefineIsDefinedOperator';
  6. import { ShaderDefineOrOperator } from './Expressions/Operators/shaderDefineOrOperator';
  7. import { ShaderDefineAndOperator } from './Expressions/Operators/shaderDefineAndOperator';
  8. import { ShaderDefineExpression } from './Expressions/shaderDefineExpression';
  9. import { ShaderDefineArithmeticOperator } from './Expressions/Operators/shaderDefineArithmeticOperator';
  10. import { ProcessingOptions } from './shaderProcessingOptions';
  11. import { _DevTools } from '../../Misc/devTools';
  12. declare type WebRequest = import("../../Misc/webRequest").WebRequest;
  13. declare type LoadFileError = import("../../Misc/fileTools").LoadFileError;
  14. declare type IOfflineProvider = import("../../Offline/IOfflineProvider").IOfflineProvider;
  15. declare type IFileRequest = import("../../Misc/fileRequest").IFileRequest;
  16. const regexSE = /defined\s*?\((.+?)\)/g;
  17. const regexSERevert = /defined\s*?\[(.+?)\]/g;
  18. /** @hidden */
  19. export class ShaderProcessor {
  20. public static Process(sourceCode: string, options: ProcessingOptions, callback: (migratedCode: string) => void) {
  21. this._ProcessIncludes(sourceCode, options, (codeWithIncludes) => {
  22. let migratedCode = this._ProcessShaderConversion(codeWithIncludes, options);
  23. callback(migratedCode);
  24. });
  25. }
  26. private static _ProcessPrecision(source: string, options: ProcessingOptions): string {
  27. const shouldUseHighPrecisionShader = options.shouldUseHighPrecisionShader;
  28. if (source.indexOf("precision highp float") === -1) {
  29. if (!shouldUseHighPrecisionShader) {
  30. source = "precision mediump float;\n" + source;
  31. } else {
  32. source = "precision highp float;\n" + source;
  33. }
  34. } else {
  35. if (!shouldUseHighPrecisionShader) { // Moving highp to mediump
  36. source = source.replace("precision highp float", "precision mediump float");
  37. }
  38. }
  39. return source;
  40. }
  41. private static _ExtractOperation(expression: string) {
  42. let regex = /defined\((.+)\)/;
  43. let match = regex.exec(expression);
  44. if (match && match.length) {
  45. return new ShaderDefineIsDefinedOperator(match[1].trim(), expression[0] === "!");
  46. }
  47. let operators = ["==", ">=", "<=", "<", ">"];
  48. let operator = "";
  49. let indexOperator = 0;
  50. for (operator of operators) {
  51. indexOperator = expression.indexOf(operator);
  52. if (indexOperator > -1) {
  53. break;
  54. }
  55. }
  56. if (indexOperator === -1) {
  57. return new ShaderDefineIsDefinedOperator(expression);
  58. }
  59. let define = expression.substring(0, indexOperator).trim();
  60. let value = expression.substring(indexOperator + operator.length).trim();
  61. return new ShaderDefineArithmeticOperator(define, operator, value);
  62. }
  63. private static _BuildSubExpression(expression: string): ShaderDefineExpression {
  64. expression = expression.replace(regexSE, "defined[$1]");
  65. const postfix = ShaderDefineExpression.infixToPostfix(expression);
  66. const stack: (string | ShaderDefineExpression)[] = [];
  67. for (let c of postfix) {
  68. if (c !== '||' && c !== '&&') {
  69. stack.push(c);
  70. } else if (stack.length >= 2) {
  71. let v1 = stack[stack.length - 1],
  72. v2 = stack[stack.length - 2];
  73. stack.length -= 2;
  74. let operator = c == '&&' ? new ShaderDefineAndOperator() : new ShaderDefineOrOperator();
  75. if (typeof(v1) === 'string') {
  76. v1 = v1.replace(regexSERevert, "defined($1)");
  77. }
  78. if (typeof(v2) === 'string') {
  79. v2 = v2.replace(regexSERevert, "defined($1)");
  80. }
  81. operator.leftOperand = typeof(v2) === 'string' ? this._ExtractOperation(v2) : v2;
  82. operator.rightOperand = typeof(v1) === 'string' ? this._ExtractOperation(v1) : v1;
  83. stack.push(operator);
  84. }
  85. }
  86. let result = stack[stack.length - 1];
  87. if (typeof(result) === 'string') {
  88. result = result.replace(regexSERevert, "defined($1)");
  89. }
  90. // note: stack.length !== 1 if there was an error in the parsing
  91. return typeof(result) === 'string' ? this._ExtractOperation(result) : result;
  92. }
  93. private static _BuildExpression(line: string, start: number): ShaderCodeTestNode {
  94. let node = new ShaderCodeTestNode();
  95. let command = line.substring(0, start);
  96. let expression = line.substring(start);
  97. expression = expression.substring(0, ((expression.indexOf("//") + 1) || (expression.length + 1)) - 1).trim();
  98. if (command === "#ifdef") {
  99. node.testExpression = new ShaderDefineIsDefinedOperator(expression);
  100. } else if (command === "#ifndef") {
  101. node.testExpression = new ShaderDefineIsDefinedOperator(expression, true);
  102. } else {
  103. node.testExpression = this._BuildSubExpression(expression);
  104. }
  105. return node;
  106. }
  107. private static _MoveCursorWithinIf(cursor: ShaderCodeCursor, rootNode: ShaderCodeConditionNode, ifNode: ShaderCodeNode) {
  108. let line = cursor.currentLine;
  109. while (this._MoveCursor(cursor, ifNode)) {
  110. line = cursor.currentLine;
  111. let first5 = line.substring(0, 5).toLowerCase();
  112. if (first5 === "#else") {
  113. let elseNode = new ShaderCodeNode();
  114. rootNode.children.push(elseNode);
  115. this._MoveCursor(cursor, elseNode);
  116. return;
  117. } else if (first5 === "#elif") {
  118. let elifNode = this._BuildExpression(line, 5);
  119. rootNode.children.push(elifNode);
  120. ifNode = elifNode;
  121. }
  122. }
  123. }
  124. private static _MoveCursor(cursor: ShaderCodeCursor, rootNode: ShaderCodeNode): boolean {
  125. while (cursor.canRead) {
  126. cursor.lineIndex++;
  127. let line = cursor.currentLine;
  128. const keywords = /(#ifdef)|(#else)|(#elif)|(#endif)|(#ifndef)|(#if)/;
  129. const matches = keywords.exec(line);
  130. if (matches && matches.length) {
  131. let keyword = matches[0];
  132. switch (keyword) {
  133. case "#ifdef": {
  134. let newRootNode = new ShaderCodeConditionNode();
  135. rootNode.children.push(newRootNode);
  136. let ifNode = this._BuildExpression(line, 6);
  137. newRootNode.children.push(ifNode);
  138. this._MoveCursorWithinIf(cursor, newRootNode, ifNode);
  139. break;
  140. }
  141. case "#else":
  142. case "#elif":
  143. return true;
  144. case "#endif":
  145. return false;
  146. case "#ifndef": {
  147. let newRootNode = new ShaderCodeConditionNode();
  148. rootNode.children.push(newRootNode);
  149. let ifNode = this._BuildExpression(line, 7);
  150. newRootNode.children.push(ifNode);
  151. this._MoveCursorWithinIf(cursor, newRootNode, ifNode);
  152. break;
  153. }
  154. case "#if": {
  155. let newRootNode = new ShaderCodeConditionNode();
  156. let ifNode = this._BuildExpression(line, 3);
  157. rootNode.children.push(newRootNode);
  158. newRootNode.children.push(ifNode);
  159. this._MoveCursorWithinIf(cursor, newRootNode, ifNode);
  160. break;
  161. }
  162. }
  163. }
  164. else {
  165. let newNode = new ShaderCodeNode();
  166. newNode.line = line;
  167. rootNode.children.push(newNode);
  168. // Detect additional defines
  169. if (line[0] === "#" && line[1] === "d") {
  170. let split = line.replace(";", "").split(" ");
  171. newNode.additionalDefineKey = split[1];
  172. if (split.length === 3) {
  173. newNode.additionalDefineValue = split[2];
  174. }
  175. }
  176. }
  177. }
  178. return false;
  179. }
  180. private static _EvaluatePreProcessors(sourceCode: string, preprocessors: { [key: string]: string }, options: ProcessingOptions): string {
  181. const rootNode = new ShaderCodeNode();
  182. let cursor = new ShaderCodeCursor();
  183. cursor.lineIndex = -1;
  184. cursor.lines = sourceCode.split("\n");
  185. // Decompose (We keep it in 2 steps so it is easier to maintain and perf hit is insignificant)
  186. this._MoveCursor(cursor, rootNode);
  187. // Recompose
  188. return rootNode.process(preprocessors, options);
  189. }
  190. private static _PreparePreProcessors(options: ProcessingOptions): { [key: string]: string } {
  191. let defines = options.defines;
  192. let preprocessors: { [key: string]: string } = {};
  193. for (var define of defines) {
  194. let keyValue = define.replace("#define", "").replace(";", "").trim();
  195. let split = keyValue.split(" ");
  196. preprocessors[split[0]] = split.length > 1 ? split[1] : "";
  197. }
  198. preprocessors["GL_ES"] = "true";
  199. preprocessors["__VERSION__"] = options.version;
  200. preprocessors[options.platformName] = "true";
  201. return preprocessors;
  202. }
  203. private static _ProcessShaderConversion(sourceCode: string, options: ProcessingOptions): string {
  204. var preparedSourceCode = this._ProcessPrecision(sourceCode, options);
  205. if (!options.processor) {
  206. return preparedSourceCode;
  207. }
  208. // Already converted
  209. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  210. return preparedSourceCode.replace("#version 300 es", "");
  211. }
  212. let defines = options.defines;
  213. let preprocessors = this._PreparePreProcessors(options);
  214. // General pre processing
  215. if (options.processor.preProcessor) {
  216. preparedSourceCode = options.processor.preProcessor(preparedSourceCode, defines, options.isFragment);
  217. }
  218. preparedSourceCode = this._EvaluatePreProcessors(preparedSourceCode, preprocessors, options);
  219. // Post processing
  220. if (options.processor.postProcessor) {
  221. preparedSourceCode = options.processor.postProcessor(preparedSourceCode, defines, options.isFragment);
  222. }
  223. return preparedSourceCode;
  224. }
  225. private static _ProcessIncludes(sourceCode: string, options: ProcessingOptions, callback: (data: any) => void): void {
  226. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  227. var match = regex.exec(sourceCode);
  228. var returnValue = new String(sourceCode);
  229. var keepProcessing = false;
  230. while (match != null) {
  231. var includeFile = match[1];
  232. // Uniform declaration
  233. if (includeFile.indexOf("__decl__") !== -1) {
  234. includeFile = includeFile.replace(/__decl__/, "");
  235. if (options.supportsUniformBuffers) {
  236. includeFile = includeFile.replace(/Vertex/, "Ubo");
  237. includeFile = includeFile.replace(/Fragment/, "Ubo");
  238. }
  239. includeFile = includeFile + "Declaration";
  240. }
  241. if (options.includesShadersStore[includeFile]) {
  242. // Substitution
  243. var includeContent = options.includesShadersStore[includeFile];
  244. if (match[2]) {
  245. var splits = match[3].split(",");
  246. for (var index = 0; index < splits.length; index += 2) {
  247. var source = new RegExp(splits[index], "g");
  248. var dest = splits[index + 1];
  249. includeContent = includeContent.replace(source, dest);
  250. }
  251. }
  252. if (match[4]) {
  253. var indexString = match[5];
  254. if (indexString.indexOf("..") !== -1) {
  255. var indexSplits = indexString.split("..");
  256. var minIndex = parseInt(indexSplits[0]);
  257. var maxIndex = parseInt(indexSplits[1]);
  258. var sourceIncludeContent = includeContent.slice(0);
  259. includeContent = "";
  260. if (isNaN(maxIndex)) {
  261. maxIndex = options.indexParameters[indexSplits[1]];
  262. }
  263. for (var i = minIndex; i < maxIndex; i++) {
  264. if (!options.supportsUniformBuffers) {
  265. // Ubo replacement
  266. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, (str: string, p1: string) => {
  267. return p1 + "{X}";
  268. });
  269. }
  270. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  271. }
  272. } else {
  273. if (!options.supportsUniformBuffers) {
  274. // Ubo replacement
  275. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, (str: string, p1: string) => {
  276. return p1 + "{X}";
  277. });
  278. }
  279. includeContent = includeContent.replace(/\{X\}/g, indexString);
  280. }
  281. }
  282. // Replace
  283. returnValue = returnValue.replace(match[0], includeContent);
  284. keepProcessing = keepProcessing || includeContent.indexOf("#include<") >= 0;
  285. } else {
  286. var includeShaderUrl = options.shadersRepository + "ShadersInclude/" + includeFile + ".fx";
  287. ShaderProcessor._FileToolsLoadFile(includeShaderUrl, (fileContent) => {
  288. options.includesShadersStore[includeFile] = fileContent as string;
  289. this._ProcessIncludes(<string>returnValue, options, callback);
  290. });
  291. return;
  292. }
  293. match = regex.exec(sourceCode);
  294. }
  295. if (keepProcessing) {
  296. this._ProcessIncludes(returnValue.toString(), options, callback);
  297. } else {
  298. callback(returnValue);
  299. }
  300. }
  301. /**
  302. * Loads a file from a url
  303. * @param url url to load
  304. * @param onSuccess callback called when the file successfully loads
  305. * @param onProgress callback called while file is loading (if the server supports this mode)
  306. * @param offlineProvider defines the offline provider for caching
  307. * @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer
  308. * @param onError callback called when the file fails to load
  309. * @returns a file request object
  310. * @hidden
  311. */
  312. public static _FileToolsLoadFile(url: string, onSuccess: (data: string | ArrayBuffer, responseURL?: string) => void, onProgress?: (ev: ProgressEvent) => void, offlineProvider?: IOfflineProvider, useArrayBuffer?: boolean, onError?: (request?: WebRequest, exception?: LoadFileError) => void): IFileRequest {
  313. throw _DevTools.WarnImport("FileTools");
  314. }
  315. }