shaderProcessor.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  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).trim();
  97. if (command === "#ifdef") {
  98. node.testExpression = new ShaderDefineIsDefinedOperator(expression);
  99. } else if (command === "#ifndef") {
  100. node.testExpression = new ShaderDefineIsDefinedOperator(expression, true);
  101. } else {
  102. node.testExpression = this._BuildSubExpression(expression);
  103. }
  104. return node;
  105. }
  106. private static _MoveCursorWithinIf(cursor: ShaderCodeCursor, rootNode: ShaderCodeConditionNode, ifNode: ShaderCodeNode) {
  107. let line = cursor.currentLine;
  108. while (this._MoveCursor(cursor, ifNode)) {
  109. line = cursor.currentLine;
  110. let first5 = line.substring(0, 5).toLowerCase();
  111. if (first5 === "#else") {
  112. let elseNode = new ShaderCodeNode();
  113. rootNode.children.push(elseNode);
  114. this._MoveCursor(cursor, elseNode);
  115. return;
  116. } else if (first5 === "#elif") {
  117. let elifNode = this._BuildExpression(line, 5);
  118. rootNode.children.push(elifNode);
  119. ifNode = elifNode;
  120. }
  121. }
  122. }
  123. private static _MoveCursor(cursor: ShaderCodeCursor, rootNode: ShaderCodeNode): boolean {
  124. while (cursor.canRead) {
  125. cursor.lineIndex++;
  126. let line = cursor.currentLine;
  127. const keywords = /(#ifdef)|(#else)|(#elif)|(#endif)|(#ifndef)|(#if)/;
  128. const matches = keywords.exec(line);
  129. if (matches && matches.length) {
  130. let keyword = matches[0];
  131. switch (keyword) {
  132. case "#ifdef": {
  133. let newRootNode = new ShaderCodeConditionNode();
  134. rootNode.children.push(newRootNode);
  135. let ifNode = this._BuildExpression(line, 6);
  136. newRootNode.children.push(ifNode);
  137. this._MoveCursorWithinIf(cursor, newRootNode, ifNode);
  138. break;
  139. }
  140. case "#else":
  141. case "#elif":
  142. return true;
  143. case "#endif":
  144. return false;
  145. case "#ifndef": {
  146. let newRootNode = new ShaderCodeConditionNode();
  147. rootNode.children.push(newRootNode);
  148. let ifNode = this._BuildExpression(line, 7);
  149. newRootNode.children.push(ifNode);
  150. this._MoveCursorWithinIf(cursor, newRootNode, ifNode);
  151. break;
  152. }
  153. case "#if": {
  154. let newRootNode = new ShaderCodeConditionNode();
  155. let ifNode = this._BuildExpression(line, 3);
  156. rootNode.children.push(newRootNode);
  157. newRootNode.children.push(ifNode);
  158. this._MoveCursorWithinIf(cursor, newRootNode, ifNode);
  159. break;
  160. }
  161. }
  162. }
  163. else {
  164. let newNode = new ShaderCodeNode();
  165. newNode.line = line;
  166. rootNode.children.push(newNode);
  167. // Detect additional defines
  168. if (line[0] === "#" && line[1] === "d") {
  169. let split = line.replace(";", "").split(" ");
  170. newNode.additionalDefineKey = split[1];
  171. if (split.length === 3) {
  172. newNode.additionalDefineValue = split[2];
  173. }
  174. }
  175. }
  176. }
  177. return false;
  178. }
  179. private static _EvaluatePreProcessors(sourceCode: string, preprocessors: { [key: string]: string }, options: ProcessingOptions): string {
  180. const rootNode = new ShaderCodeNode();
  181. let cursor = new ShaderCodeCursor();
  182. cursor.lineIndex = -1;
  183. cursor.lines = sourceCode.split("\n");
  184. // Decompose (We keep it in 2 steps so it is easier to maintain and perf hit is insignificant)
  185. this._MoveCursor(cursor, rootNode);
  186. // Recompose
  187. return rootNode.process(preprocessors, options);
  188. }
  189. private static _PreparePreProcessors(options: ProcessingOptions): { [key: string]: string } {
  190. let defines = options.defines;
  191. let preprocessors: { [key: string]: string } = {};
  192. for (var define of defines) {
  193. let keyValue = define.replace("#define", "").replace(";", "").trim();
  194. let split = keyValue.split(" ");
  195. preprocessors[split[0]] = split.length > 1 ? split[1] : "";
  196. }
  197. preprocessors["GL_ES"] = "true";
  198. preprocessors["__VERSION__"] = options.version;
  199. preprocessors[options.platformName] = "true";
  200. return preprocessors;
  201. }
  202. private static _ProcessShaderConversion(sourceCode: string, options: ProcessingOptions): string {
  203. var preparedSourceCode = this._ProcessPrecision(sourceCode, options);
  204. if (!options.processor) {
  205. return preparedSourceCode;
  206. }
  207. // Already converted
  208. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  209. return preparedSourceCode.replace("#version 300 es", "");
  210. }
  211. let defines = options.defines;
  212. let preprocessors = this._PreparePreProcessors(options);
  213. // General pre processing
  214. if (options.processor.preProcessor) {
  215. preparedSourceCode = options.processor.preProcessor(preparedSourceCode, defines, options.isFragment);
  216. }
  217. preparedSourceCode = this._EvaluatePreProcessors(preparedSourceCode, preprocessors, options);
  218. // Post processing
  219. if (options.processor.postProcessor) {
  220. preparedSourceCode = options.processor.postProcessor(preparedSourceCode, defines, options.isFragment);
  221. }
  222. return preparedSourceCode;
  223. }
  224. private static _ProcessIncludes(sourceCode: string, options: ProcessingOptions, callback: (data: any) => void): void {
  225. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  226. var match = regex.exec(sourceCode);
  227. var returnValue = new String(sourceCode);
  228. while (match != null) {
  229. var includeFile = match[1];
  230. // Uniform declaration
  231. if (includeFile.indexOf("__decl__") !== -1) {
  232. includeFile = includeFile.replace(/__decl__/, "");
  233. if (options.supportsUniformBuffers) {
  234. includeFile = includeFile.replace(/Vertex/, "Ubo");
  235. includeFile = includeFile.replace(/Fragment/, "Ubo");
  236. }
  237. includeFile = includeFile + "Declaration";
  238. }
  239. if (options.includesShadersStore[includeFile]) {
  240. // Substitution
  241. var includeContent = options.includesShadersStore[includeFile];
  242. if (match[2]) {
  243. var splits = match[3].split(",");
  244. for (var index = 0; index < splits.length; index += 2) {
  245. var source = new RegExp(splits[index], "g");
  246. var dest = splits[index + 1];
  247. includeContent = includeContent.replace(source, dest);
  248. }
  249. }
  250. if (match[4]) {
  251. var indexString = match[5];
  252. if (indexString.indexOf("..") !== -1) {
  253. var indexSplits = indexString.split("..");
  254. var minIndex = parseInt(indexSplits[0]);
  255. var maxIndex = parseInt(indexSplits[1]);
  256. var sourceIncludeContent = includeContent.slice(0);
  257. includeContent = "";
  258. if (isNaN(maxIndex)) {
  259. maxIndex = options.indexParameters[indexSplits[1]];
  260. }
  261. for (var i = minIndex; i < maxIndex; i++) {
  262. if (!options.supportsUniformBuffers) {
  263. // Ubo replacement
  264. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, (str: string, p1: string) => {
  265. return p1 + "{X}";
  266. });
  267. }
  268. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  269. }
  270. } else {
  271. if (!options.supportsUniformBuffers) {
  272. // Ubo replacement
  273. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, (str: string, p1: string) => {
  274. return p1 + "{X}";
  275. });
  276. }
  277. includeContent = includeContent.replace(/\{X\}/g, indexString);
  278. }
  279. }
  280. // Replace
  281. returnValue = returnValue.replace(match[0], includeContent);
  282. } else {
  283. var includeShaderUrl = options.shadersRepository + "ShadersInclude/" + includeFile + ".fx";
  284. ShaderProcessor._FileToolsLoadFile(includeShaderUrl, (fileContent) => {
  285. options.includesShadersStore[includeFile] = fileContent as string;
  286. this._ProcessIncludes(<string>returnValue, options, callback);
  287. });
  288. return;
  289. }
  290. match = regex.exec(sourceCode);
  291. }
  292. callback(returnValue);
  293. }
  294. /**
  295. * Loads a file from a url
  296. * @param url url to load
  297. * @param onSuccess callback called when the file successfully loads
  298. * @param onProgress callback called while file is loading (if the server supports this mode)
  299. * @param offlineProvider defines the offline provider for caching
  300. * @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer
  301. * @param onError callback called when the file fails to load
  302. * @returns a file request object
  303. * @hidden
  304. */
  305. 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 {
  306. throw _DevTools.WarnImport("FileTools");
  307. }
  308. }