shaderCodeInliner.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. interface IInlineFunctionDescr {
  2. name: string;
  3. type: string;
  4. parameters: string[];
  5. body: string;
  6. callIndex: number;
  7. }
  8. /**
  9. * Class used to inline functions in shader code
  10. */
  11. export class ShaderCodeInliner {
  12. private static readonly _RegexpFindFunctionNameAndType = /((\s+?)(\w+)\s+(\w+)\s*?)$/;
  13. private _sourceCode: string;
  14. private _functionDescr: IInlineFunctionDescr[];
  15. private _numMaxIterations: number;
  16. /** Gets or sets the token used to mark the functions to inline */
  17. public inlineToken: string;
  18. /** Gets or sets the debug mode */
  19. public debug: boolean = false;
  20. /** Gets the code after the inlining process */
  21. public get code(): string {
  22. return this._sourceCode;
  23. }
  24. /**
  25. * Initializes the inliner
  26. * @param sourceCode shader code source to inline
  27. * @param numMaxIterations maximum number of iterations (used to detect recursive calls)
  28. */
  29. constructor(sourceCode: string, numMaxIterations = 20) {
  30. this._sourceCode = sourceCode;
  31. this._numMaxIterations = numMaxIterations;
  32. this._functionDescr = [];
  33. this.inlineToken = "#define inline";
  34. }
  35. /**
  36. * Start the processing of the shader code
  37. */
  38. public processCode() {
  39. if (this.debug) {
  40. console.log(`Start inlining process (code size=${this._sourceCode.length})...`);
  41. }
  42. this._collectFunctions();
  43. this._processInlining(this._numMaxIterations);
  44. if (this.debug) {
  45. console.log("End of inlining process.");
  46. }
  47. }
  48. private _collectFunctions() {
  49. let startIndex = 0;
  50. while (startIndex < this._sourceCode.length) {
  51. // locate the function to inline and extract its name
  52. const inlineTokenIndex = this._sourceCode.indexOf(this.inlineToken, startIndex);
  53. if (inlineTokenIndex < 0) {
  54. break;
  55. }
  56. const funcParamsStartIndex = this._sourceCode.indexOf("(", inlineTokenIndex + this.inlineToken.length);
  57. if (funcParamsStartIndex < 0) {
  58. if (this.debug) {
  59. console.warn(`Could not find the opening parenthesis after the token. startIndex=${startIndex}`);
  60. }
  61. startIndex = inlineTokenIndex + this.inlineToken.length;
  62. continue;
  63. }
  64. const funcNameMatch = ShaderCodeInliner._RegexpFindFunctionNameAndType.exec(this._sourceCode.substring(inlineTokenIndex + this.inlineToken.length, funcParamsStartIndex));
  65. if (!funcNameMatch) {
  66. if (this.debug) {
  67. console.warn(`Could not extract the name/type of the function from: ${this._sourceCode.substring(inlineTokenIndex + this.inlineToken.length, funcParamsStartIndex)}`);
  68. }
  69. startIndex = inlineTokenIndex + this.inlineToken.length;
  70. continue;
  71. }
  72. const [funcType, funcName] = [funcNameMatch[3], funcNameMatch[4]];
  73. // extract the parameters of the function as a whole string (without the leading / trailing parenthesis)
  74. const funcParamsEndIndex = this._extractBetweenMarkers('(', ')', this._sourceCode, funcParamsStartIndex);
  75. if (funcParamsEndIndex < 0) {
  76. if (this.debug) {
  77. console.warn(`Could not extract the parameters the function '${funcName}' (type=${funcType}). funcParamsStartIndex=${funcParamsStartIndex}`);
  78. }
  79. startIndex = inlineTokenIndex + this.inlineToken.length;
  80. continue;
  81. }
  82. const funcParams = this._sourceCode.substring(funcParamsStartIndex + 1, funcParamsEndIndex);
  83. // extract the body of the function (with the curly brackets)
  84. const funcBodyStartIndex = this._skipWhitespaces(this._sourceCode, funcParamsEndIndex + 1);
  85. if (funcBodyStartIndex === this._sourceCode.length) {
  86. if (this.debug) {
  87. console.warn(`Could not extract the body of the function '${funcName}' (type=${funcType}). funcParamsEndIndex=${funcParamsEndIndex}`);
  88. }
  89. startIndex = inlineTokenIndex + this.inlineToken.length;
  90. continue;
  91. }
  92. const funcBodyEndIndex = this._extractBetweenMarkers('{', '}', this._sourceCode, funcBodyStartIndex);
  93. if (funcBodyEndIndex < 0) {
  94. if (this.debug) {
  95. console.warn(`Could not extract the body of the function '${funcName}' (type=${funcType}). funcBodyStartIndex=${funcBodyStartIndex}`);
  96. }
  97. startIndex = inlineTokenIndex + this.inlineToken.length;
  98. continue;
  99. }
  100. const funcBody = this._sourceCode.substring(funcBodyStartIndex, funcBodyEndIndex + 1);
  101. // process the parameters: extract each names
  102. const params = this._removeComments(funcParams).split(",");
  103. const paramNames = [];
  104. for (let p = 0; p < params.length; ++p) {
  105. const param = params[p].trim();
  106. const idx = param.lastIndexOf(" ");
  107. if (idx >= 0) {
  108. paramNames.push(param.substring(idx + 1));
  109. }
  110. }
  111. if (funcType !== 'void') {
  112. // for functions that return a value, we will replace "return" by "tempvarname = ", tempvarname being a unique generated name
  113. paramNames.push('return');
  114. }
  115. // collect the function
  116. this._functionDescr.push({
  117. "name": funcName,
  118. "type": funcType,
  119. "parameters": paramNames,
  120. "body": funcBody,
  121. "callIndex": 0,
  122. });
  123. startIndex = funcBodyEndIndex + 1;
  124. // remove the function from the source code
  125. const partBefore = inlineTokenIndex > 0 ? this._sourceCode.substring(0, inlineTokenIndex) : "";
  126. const partAfter = funcBodyEndIndex + 1 < this._sourceCode.length - 1 ? this._sourceCode.substring(funcBodyEndIndex + 1) : "";
  127. this._sourceCode = partBefore + partAfter;
  128. startIndex -= funcBodyEndIndex + 1 - inlineTokenIndex;
  129. }
  130. if (this.debug) {
  131. console.log(`Collect functions: ${this._functionDescr.length} functions found. functionDescr=`, this._functionDescr);
  132. }
  133. }
  134. private _processInlining(numMaxIterations: number = 20): boolean {
  135. while (numMaxIterations-- >= 0) {
  136. if (!this._replaceFunctionCallsByCode()) {
  137. break;
  138. }
  139. }
  140. if (this.debug) {
  141. console.log(`numMaxIterations is ${numMaxIterations} after inlining process`);
  142. }
  143. return numMaxIterations >= 0;
  144. }
  145. private _extractBetweenMarkers(markerOpen: string, markerClose: string, block: string, startIndex: number): number {
  146. let currPos = startIndex,
  147. openMarkers = 0,
  148. waitForChar = '';
  149. while (currPos < block.length) {
  150. let currChar = block.charAt(currPos);
  151. if (!waitForChar) {
  152. switch (currChar) {
  153. case markerOpen:
  154. openMarkers++;
  155. break;
  156. case markerClose:
  157. openMarkers--;
  158. break;
  159. case '"':
  160. case "'":
  161. case "`":
  162. waitForChar = currChar;
  163. break;
  164. case '/':
  165. if (currPos + 1 < block.length) {
  166. const nextChar = block.charAt(currPos + 1);
  167. if (nextChar === '/') {
  168. waitForChar = '\n';
  169. } else if (nextChar === '*') {
  170. waitForChar = '*/';
  171. }
  172. }
  173. break;
  174. }
  175. } else {
  176. if (currChar === waitForChar) {
  177. if (waitForChar === '"' || waitForChar === "'") {
  178. block.charAt(currPos - 1) !== '\\' && (waitForChar = '');
  179. } else {
  180. waitForChar = '';
  181. }
  182. } else if (waitForChar === '*/' && currChar === '*' && currPos + 1 < block.length) {
  183. block.charAt(currPos + 1) === '/' && (waitForChar = '');
  184. if (waitForChar === '') {
  185. currPos++;
  186. }
  187. }
  188. }
  189. currPos++ ;
  190. if (openMarkers === 0) {
  191. break;
  192. }
  193. }
  194. return openMarkers === 0 ? currPos - 1 : -1;
  195. }
  196. private _skipWhitespaces(s: string, index: number): number {
  197. while (index < s.length) {
  198. const c = s[index];
  199. if (c !== ' ' && c !== '\n' && c !== '\r' && c !== '\t' && c !== '\u000a' && c !== '\u00a0') {
  200. break;
  201. }
  202. index++;
  203. }
  204. return index;
  205. }
  206. private _removeComments(block: string): string {
  207. let currPos = 0,
  208. waitForChar = '',
  209. inComments = false,
  210. s = [];
  211. while (currPos < block.length) {
  212. let currChar = block.charAt(currPos);
  213. if (!waitForChar) {
  214. switch (currChar) {
  215. case '"':
  216. case "'":
  217. case "`":
  218. waitForChar = currChar;
  219. break;
  220. case '/':
  221. if (currPos + 1 < block.length) {
  222. const nextChar = block.charAt(currPos + 1);
  223. if (nextChar === '/') {
  224. waitForChar = '\n';
  225. inComments = true;
  226. } else if (nextChar === '*') {
  227. waitForChar = '*/';
  228. inComments = true;
  229. }
  230. }
  231. break;
  232. }
  233. if (!inComments) {
  234. s.push(currChar);
  235. }
  236. } else {
  237. if (currChar === waitForChar) {
  238. if (waitForChar === '"' || waitForChar === "'") {
  239. block.charAt(currPos - 1) !== '\\' && (waitForChar = '');
  240. s.push(currChar);
  241. } else {
  242. waitForChar = '';
  243. inComments = false;
  244. }
  245. } else if (waitForChar === '*/' && currChar === '*' && currPos + 1 < block.length) {
  246. block.charAt(currPos + 1) === '/' && (waitForChar = '');
  247. if (waitForChar === '') {
  248. inComments = false;
  249. currPos++;
  250. }
  251. } else {
  252. if (!inComments) {
  253. s.push(currChar);
  254. }
  255. }
  256. }
  257. currPos++ ;
  258. }
  259. return s.join('');
  260. }
  261. private _replaceFunctionCallsByCode(): boolean {
  262. let doAgain = false;
  263. for (const func of this._functionDescr) {
  264. const { name, type, parameters, body } = func;
  265. let startIndex = 0;
  266. while (startIndex < this._sourceCode.length) {
  267. // Look for the function name in the source code
  268. const functionCallIndex = this._sourceCode.indexOf(name, startIndex);
  269. if (functionCallIndex < 0) {
  270. break;
  271. }
  272. // Find the opening parenthesis
  273. const callParamsStartIndex = this._skipWhitespaces(this._sourceCode, functionCallIndex + name.length);
  274. if (callParamsStartIndex === this._sourceCode.length || this._sourceCode.charAt(callParamsStartIndex) !== '(') {
  275. startIndex = functionCallIndex + name.length;
  276. continue;
  277. }
  278. // extract the parameters of the function call as a whole string (without the leading / trailing parenthesis)
  279. const callParamsEndIndex = this._extractBetweenMarkers('(', ')', this._sourceCode, callParamsStartIndex);
  280. if (callParamsEndIndex < 0) {
  281. if (this.debug) {
  282. console.warn(`Could not extract the parameters of the function call. Function '${name}' (type=${type}). callParamsStartIndex=${callParamsStartIndex}`);
  283. }
  284. startIndex = functionCallIndex + name.length;
  285. continue;
  286. }
  287. const callParams = this._sourceCode.substring(callParamsStartIndex + 1, callParamsEndIndex);
  288. // process the parameter call: extract each names
  289. const params = this._removeComments(callParams).split(",");
  290. const paramNames = [];
  291. for (let p = 0; p < params.length; ++p) {
  292. const param = params[p].trim();
  293. paramNames.push(param);
  294. }
  295. const retParamName = type !== 'void' ? name + '_' + (func.callIndex++) : null;
  296. if (retParamName) {
  297. paramNames.push(retParamName + ' =');
  298. }
  299. if (paramNames.length !== parameters.length) {
  300. if (this.debug) {
  301. console.warn(`Invalid function call: not the same number of parameters for the call than the number expected by the function. Function '${name}' (type=${type}). function parameters=${parameters}, call parameters=${paramNames}`);
  302. }
  303. startIndex = functionCallIndex + name.length;
  304. continue;
  305. }
  306. startIndex = callParamsEndIndex + 1;
  307. // replace the function call by the body function
  308. const funcBody = this._replaceNames(body, parameters, paramNames);
  309. let partBefore = functionCallIndex > 0 ? this._sourceCode.substring(0, functionCallIndex) : "";
  310. let partAfter = callParamsEndIndex + 1 < this._sourceCode.length - 1 ? this._sourceCode.substring(callParamsEndIndex + 1) : "";
  311. if (retParamName) {
  312. // case where the function returns a value. We generate:
  313. // FUNCTYPE retParamName;
  314. // {function body}
  315. // and replace the function call by retParamName
  316. const injectDeclarationIndex = this._findBackward(this._sourceCode, functionCallIndex - 1, '\n');
  317. partBefore = this._sourceCode.substring(0, injectDeclarationIndex + 1);
  318. let partBetween = this._sourceCode.substring(injectDeclarationIndex + 1, functionCallIndex);
  319. this._sourceCode = partBefore + type + " " + retParamName + ";\n" + funcBody + "\n" + partBetween + retParamName + partAfter;
  320. if (this.debug) {
  321. console.log(`Replace function call by code. Function '${name}' (type=${type}). injectDeclarationIndex=${injectDeclarationIndex}`);
  322. }
  323. } else {
  324. // simple case where the return value of the function is "void"
  325. this._sourceCode = partBefore + funcBody + partAfter;
  326. startIndex += funcBody.length - (callParamsEndIndex + 1 - functionCallIndex);
  327. if (this.debug) {
  328. console.log(`Replace function call by code. Function '${name}' (type=${type}). functionCallIndex=${functionCallIndex}`);
  329. }
  330. }
  331. doAgain = true;
  332. }
  333. }
  334. return doAgain;
  335. }
  336. private _findBackward(s: string, index: number, c: string): number {
  337. while (index >= 0 && s.charAt(index) !== c) {
  338. index--;
  339. }
  340. return index;
  341. }
  342. private _escapeRegExp(s: string): string {
  343. return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  344. }
  345. private _replaceNames(code: string, sources: string[], destinations: string[]): string {
  346. for (let i = 0; i < sources.length; ++i) {
  347. const source = new RegExp(this._escapeRegExp(sources[i]), 'g'),
  348. destination = destinations[i];
  349. code = code.replace(source, destination);
  350. }
  351. return code;
  352. }
  353. }