GLSLDecoder.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983
  1. import { Program, FunctionDeclaration, For, AccessorElements, Ternary, Varying, DynamicElement, StaticElement, FunctionParameter, Unary, Conditional, VariableDeclaration, Operator, Number, String, FunctionCall, Return, Accessor, Uniform } from './AST.js';
  2. const unaryOperators = [
  3. '+', '-', '~', '!', '++', '--'
  4. ];
  5. const precedenceOperators = [
  6. '*', '/', '%',
  7. '-', '+',
  8. '<<', '>>',
  9. '<', '>', '<=', '>=',
  10. '==', '!=',
  11. '&',
  12. '^',
  13. '|',
  14. '&&',
  15. '^^',
  16. '||',
  17. '?',
  18. '=',
  19. '+=', '-=', '*=', '/=', '%=', '^=', '&=', '|=', '<<=', '>>=',
  20. ','
  21. ].reverse();
  22. const associativityRightToLeft = [
  23. '=',
  24. '+=', '-=', '*=', '/=', '%=', '^=', '&=', '|=', '<<=', '>>=',
  25. ',',
  26. '?',
  27. ':'
  28. ];
  29. const spaceRegExp = /^((\t| )\n*)+/;
  30. const lineRegExp = /^\n+/;
  31. const commentRegExp = /^\/\*[\s\S]*?\*\//;
  32. const inlineCommentRegExp = /^\/\/.*?(\n|$)/;
  33. const numberRegExp = /^((0x\w+)|(\.?\d+\.?\d*((e-?\d+)|\w)?))/;
  34. const stringDoubleRegExp = /^(\"((?:[^"\\]|\\.)*)\")/;
  35. const stringSingleRegExp = /^(\'((?:[^'\\]|\\.)*)\')/;
  36. const literalRegExp = /^[A-Za-z](\w|\.)*/;
  37. const operatorsRegExp = new RegExp( '^(\\' + [
  38. '<<=', '>>=', '++', '--', '<<', '>>', '+=', '-=', '*=', '/=', '%=', '&=', '^^', '^=', '|=',
  39. '<=', '>=', '==', '!=', '&&', '||',
  40. '(', ')', '[', ']', '{', '}',
  41. '.', ',', ';', '!', '=', '~', '*', '/', '%', '+', '-', '<', '>', '&', '^', '|', '?', ':', '#'
  42. ].join( '$' ).split( '' ).join( '\\' ).replace( /\\\$/g, '|' ) + ')' );
  43. function getGroupDelta( str ) {
  44. if ( str === '(' || str === '[' || str === '{' ) return 1;
  45. if ( str === ')' || str === ']' || str === '}' ) return - 1;
  46. return 0;
  47. }
  48. class Token {
  49. constructor( tokenizer, type, str, pos ) {
  50. this.tokenizer = tokenizer;
  51. this.type = type;
  52. this.str = str;
  53. this.pos = pos;
  54. this.tag = null;
  55. }
  56. get endPos() {
  57. return this.pos + this.str.length;
  58. }
  59. get isNumber() {
  60. return this.type === Token.NUMBER;
  61. }
  62. get isString() {
  63. return this.type === Token.STRING;
  64. }
  65. get isLiteral() {
  66. return this.type === Token.LITERAL;
  67. }
  68. get isOperator() {
  69. return this.type === Token.OPERATOR;
  70. }
  71. }
  72. Token.LINE = 'line';
  73. Token.COMMENT = 'comment';
  74. Token.NUMBER = 'number';
  75. Token.STRING = 'string';
  76. Token.LITERAL = 'literal';
  77. Token.OPERATOR = 'operator';
  78. const TokenParserList = [
  79. { type: Token.LINE, regexp: lineRegExp, isTag: true },
  80. { type: Token.COMMENT, regexp: commentRegExp, isTag: true },
  81. { type: Token.COMMENT, regexp: inlineCommentRegExp, isTag: true },
  82. { type: Token.NUMBER, regexp: numberRegExp },
  83. { type: Token.STRING, regexp: stringDoubleRegExp, group: 2 },
  84. { type: Token.STRING, regexp: stringSingleRegExp, group: 2 },
  85. { type: Token.LITERAL, regexp: literalRegExp },
  86. { type: Token.OPERATOR, regexp: operatorsRegExp }
  87. ];
  88. class Tokenizer {
  89. constructor( source ) {
  90. this.source = source;
  91. this.position = 0;
  92. this.tokens = [];
  93. }
  94. tokenize() {
  95. let token = this.readToken();
  96. while ( token ) {
  97. this.tokens.push( token );
  98. token = this.readToken();
  99. }
  100. return this;
  101. }
  102. skip( ...params ) {
  103. let remainingCode = this.source.substr( this.position );
  104. let i = params.length;
  105. while ( i -- ) {
  106. const skip = params[ i ].exec( remainingCode );
  107. const skipLength = skip ? skip[ 0 ].length : 0;
  108. if ( skipLength > 0 ) {
  109. this.position += skipLength;
  110. remainingCode = this.source.substr( this.position );
  111. // re-skip, new remainingCode is generated
  112. // maybe exist previous regexp non detected
  113. i = params.length;
  114. }
  115. }
  116. return remainingCode;
  117. }
  118. readToken() {
  119. const remainingCode = this.skip( spaceRegExp );
  120. for ( var i = 0; i < TokenParserList.length; i ++ ) {
  121. const parser = TokenParserList[ i ];
  122. const result = parser.regexp.exec( remainingCode );
  123. if ( result ) {
  124. const token = new Token( this, parser.type, result[ parser.group || 0 ], this.position );
  125. this.position += result[ 0 ].length;
  126. if ( parser.isTag ) {
  127. const nextToken = this.readToken();
  128. if ( nextToken ) {
  129. nextToken.tag = token;
  130. }
  131. return nextToken;
  132. }
  133. return token;
  134. }
  135. }
  136. }
  137. }
  138. const isType = ( str ) => /void|bool|float|u?int|(u|i)?vec[234]/.test( str );
  139. class GLSLDecoder {
  140. constructor() {
  141. this.index = 0;
  142. this.tokenizer = null;
  143. this.keywords = [];
  144. this._currentFunction = null;
  145. this.addPolyfill( 'gl_FragCoord', 'vec3 gl_FragCoord = vec3( viewportCoordinate.x, viewportCoordinate.y.oneMinus(), viewportCoordinate.z );' );
  146. }
  147. addPolyfill( name, polyfill ) {
  148. this.keywords.push( { name, polyfill } );
  149. return this;
  150. }
  151. get tokens() {
  152. return this.tokenizer.tokens;
  153. }
  154. readToken() {
  155. return this.tokens[ this.index ++ ];
  156. }
  157. getToken( offset = 0 ) {
  158. return this.tokens[ this.index + offset ];
  159. }
  160. getTokensUntil( str, tokens, offset = 0 ) {
  161. const output = [];
  162. let groupIndex = 0;
  163. for ( let i = offset; i < tokens.length; i ++ ) {
  164. const token = tokens[ i ];
  165. groupIndex += getGroupDelta( token.str );
  166. output.push( token );
  167. if ( groupIndex === 0 && token.str === str ) {
  168. break;
  169. }
  170. }
  171. return output;
  172. }
  173. readTokensUntil( str ) {
  174. const tokens = this.getTokensUntil( str, this.tokens, this.index );
  175. this.index += tokens.length;
  176. return tokens;
  177. }
  178. parseExpressionFromTokens( tokens ) {
  179. if ( tokens.length === 0 ) return null;
  180. const firstToken = tokens[ 0 ];
  181. const lastToken = tokens[ tokens.length - 1 ];
  182. // precedence operators
  183. let groupIndex = 0;
  184. for ( const operator of precedenceOperators ) {
  185. const parseToken = ( i, inverse = false ) => {
  186. const token = tokens[ i ];
  187. groupIndex += getGroupDelta( token.str );
  188. if ( ! token.isOperator || i === 0 || i === tokens.length - 1 ) return;
  189. if ( groupIndex === 0 && token.str === operator ) {
  190. if ( operator === '?' ) {
  191. const conditionTokens = tokens.slice( 0, i );
  192. const leftTokens = this.getTokensUntil( ':', tokens, i + 1 ).slice( 0, - 1 );
  193. const rightTokens = tokens.slice( i + leftTokens.length + 2 );
  194. const condition = this.parseExpressionFromTokens( conditionTokens );
  195. const left = this.parseExpressionFromTokens( leftTokens );
  196. const right = this.parseExpressionFromTokens( rightTokens );
  197. return new Ternary( condition, left, right );
  198. } else {
  199. const left = this.parseExpressionFromTokens( tokens.slice( 0, i ) );
  200. const right = this.parseExpressionFromTokens( tokens.slice( i + 1, tokens.length ) );
  201. return this._evalOperator( new Operator( operator, left, right ) );
  202. }
  203. }
  204. if ( inverse ) {
  205. if ( groupIndex > 0 ) {
  206. return this.parseExpressionFromTokens( tokens.slice( i ) );
  207. }
  208. } else {
  209. if ( groupIndex < 0 ) {
  210. return this.parseExpressionFromTokens( tokens.slice( 0, i ) );
  211. }
  212. }
  213. };
  214. if ( associativityRightToLeft.includes( operator ) ) {
  215. for ( let i = 0; i < tokens.length; i ++ ) {
  216. const result = parseToken( i );
  217. if ( result ) return result;
  218. }
  219. } else {
  220. for ( let i = tokens.length - 1; i >= 0; i -- ) {
  221. const result = parseToken( i, true );
  222. if ( result ) return result;
  223. }
  224. }
  225. }
  226. // unary operators (before)
  227. if ( firstToken.isOperator ) {
  228. for ( const operator of unaryOperators ) {
  229. if ( firstToken.str === operator ) {
  230. const right = this.parseExpressionFromTokens( tokens.slice( 1 ) );
  231. return new Unary( operator, right );
  232. }
  233. }
  234. }
  235. // unary operators (after)
  236. if ( lastToken.isOperator ) {
  237. for ( const operator of unaryOperators ) {
  238. if ( lastToken.str === operator ) {
  239. const left = this.parseExpressionFromTokens( tokens.slice( 0, tokens.length - 1 ) );
  240. return new Unary( operator, left, true );
  241. }
  242. }
  243. }
  244. // groups
  245. if ( firstToken.str === '(' ) {
  246. const leftTokens = this.getTokensUntil( ')', tokens );
  247. const left = this.parseExpressionFromTokens( leftTokens.slice( 1, leftTokens.length - 1 ) );
  248. const operator = tokens[ leftTokens.length ];
  249. if ( operator ) {
  250. const rightTokens = tokens.slice( leftTokens.length + 1 );
  251. const right = this.parseExpressionFromTokens( rightTokens );
  252. return this._evalOperator( new Operator( operator.str, left, right ) );
  253. }
  254. return left;
  255. }
  256. // primitives and accessors
  257. if ( firstToken.isNumber ) {
  258. let type;
  259. const isHex = /^(0x)/.test( firstToken.str );
  260. if ( isHex ) type = 'int';
  261. else if ( /u$/.test( firstToken.str ) ) type = 'uint';
  262. else if ( /f|e|\./.test( firstToken.str ) ) type = 'float';
  263. else type = 'int';
  264. let str = firstToken.str.replace( /u|i$/, '' );
  265. if ( isHex === false ) {
  266. str = str.replace( /f$/, '' );
  267. }
  268. return new Number( str, type );
  269. } else if ( firstToken.isString ) {
  270. return new String( firstToken.str );
  271. } else if ( firstToken.isLiteral ) {
  272. if ( firstToken.str === 'return' ) {
  273. return new Return( this.parseExpressionFromTokens( tokens.slice( 1 ) ) );
  274. }
  275. const secondToken = tokens[ 1 ];
  276. if ( secondToken ) {
  277. if ( secondToken.str === '(' ) {
  278. // function call
  279. const paramsTokens = this.parseFunctionParametersFromTokens( tokens.slice( 2, tokens.length - 1 ) );
  280. return new FunctionCall( firstToken.str, paramsTokens );
  281. } else if ( secondToken.str === '[' ) {
  282. // array accessor
  283. const elements = [];
  284. let currentTokens = tokens.slice( 1 );
  285. while ( currentTokens.length > 0 ) {
  286. const token = currentTokens[ 0 ];
  287. if ( token.str === '[' ) {
  288. const accessorTokens = this.getTokensUntil( ']', currentTokens );
  289. const element = this.parseExpressionFromTokens( accessorTokens.slice( 1, accessorTokens.length - 1 ) );
  290. currentTokens = currentTokens.slice( accessorTokens.length );
  291. elements.push( new DynamicElement( element ) );
  292. } else if ( token.str === '.' ) {
  293. const accessorTokens = currentTokens.slice( 1, 2 );
  294. const element = this.parseExpressionFromTokens( accessorTokens );
  295. currentTokens = currentTokens.slice( 2 );
  296. elements.push( new StaticElement( element ) );
  297. } else {
  298. console.error( 'Unknown accessor expression', token );
  299. break;
  300. }
  301. }
  302. return new AccessorElements( firstToken.str, elements );
  303. }
  304. }
  305. return new Accessor( firstToken.str );
  306. }
  307. }
  308. parseFunctionParametersFromTokens( tokens ) {
  309. if ( tokens.length === 0 ) return [];
  310. const expression = this.parseExpressionFromTokens( tokens );
  311. const params = [];
  312. let current = expression;
  313. while ( current.type === ',' ) {
  314. params.push( current.left );
  315. current = current.right;
  316. }
  317. params.push( current );
  318. return params;
  319. }
  320. parseExpression() {
  321. const tokens = this.readTokensUntil( ';' );
  322. const exp = this.parseExpressionFromTokens( tokens.slice( 0, tokens.length - 1 ) );
  323. return exp;
  324. }
  325. parseFunctionParams( tokens ) {
  326. const params = [];
  327. for ( let i = 0; i < tokens.length; i ++ ) {
  328. const immutable = tokens[ i ].str === 'const';
  329. if ( immutable ) i ++;
  330. let qualifier = tokens[ i ].str;
  331. if ( /^(in|out|inout)$/.test( qualifier ) ) {
  332. i ++;
  333. } else {
  334. qualifier = null;
  335. }
  336. const type = tokens[ i ++ ].str;
  337. const name = tokens[ i ++ ].str;
  338. params.push( new FunctionParameter( type, name, qualifier, immutable ) );
  339. if ( tokens[ i ] && tokens[ i ].str !== ',' ) throw new Error( 'Expected ","' );
  340. }
  341. return params;
  342. }
  343. parseFunction() {
  344. const type = this.readToken().str;
  345. const name = this.readToken().str;
  346. const paramsTokens = this.readTokensUntil( ')' );
  347. const params = this.parseFunctionParams( paramsTokens.slice( 1, paramsTokens.length - 1 ) );
  348. const func = new FunctionDeclaration( type, name, params );
  349. this._currentFunction = func;
  350. this.parseBlock( func );
  351. this._currentFunction = null;
  352. return func;
  353. }
  354. parseVariablesFromToken( tokens, type ) {
  355. let index = 0;
  356. const immutable = tokens[ 0 ].str === 'const';
  357. if ( immutable ) index ++;
  358. type = type || tokens[ index ++ ].str;
  359. const name = tokens[ index ++ ].str;
  360. const token = tokens[ index ];
  361. let init = null;
  362. let next = null;
  363. if ( token ) {
  364. const initTokens = this.getTokensUntil( ',', tokens, index );
  365. if ( initTokens[ 0 ].str === '=' ) {
  366. const expressionTokens = initTokens.slice( 1 );
  367. if ( expressionTokens[ expressionTokens.length - 1 ].str === ',' ) expressionTokens.pop();
  368. init = this.parseExpressionFromTokens( expressionTokens );
  369. }
  370. const nextTokens = tokens.slice( initTokens.length + ( index - 1 ) );
  371. if ( nextTokens[ 0 ] && nextTokens[ 0 ].str === ',' ) {
  372. next = this.parseVariablesFromToken( nextTokens.slice( 1 ), type );
  373. }
  374. }
  375. const variable = new VariableDeclaration( type, name, init, next, immutable );
  376. return variable;
  377. }
  378. parseVariables() {
  379. const tokens = this.readTokensUntil( ';' );
  380. return this.parseVariablesFromToken( tokens.slice( 0, tokens.length - 1 ) );
  381. }
  382. parseUniform() {
  383. const tokens = this.readTokensUntil( ';' );
  384. const type = tokens[ 1 ].str;
  385. const name = tokens[ 2 ].str;
  386. return new Uniform( type, name );
  387. }
  388. parseVarying() {
  389. const tokens = this.readTokensUntil( ';' );
  390. const type = tokens[ 1 ].str;
  391. const name = tokens[ 2 ].str;
  392. return new Varying( type, name );
  393. }
  394. parseReturn() {
  395. this.readToken(); // skip 'return'
  396. const expression = this.parseExpression();
  397. return new Return( expression );
  398. }
  399. parseFor() {
  400. this.readToken(); // skip 'for'
  401. const forTokens = this.readTokensUntil( ')' ).slice( 1, - 1 );
  402. const initializationTokens = this.getTokensUntil( ';', forTokens, 0 ).slice( 0, - 1 );
  403. const conditionTokens = this.getTokensUntil( ';', forTokens, initializationTokens.length + 1 ).slice( 0, - 1 );
  404. const afterthoughtTokens = forTokens.slice( initializationTokens.length + conditionTokens.length + 2 );
  405. let initialization;
  406. if ( initializationTokens[ 0 ] && isType( initializationTokens[ 0 ].str ) ) {
  407. initialization = this.parseVariablesFromToken( initializationTokens );
  408. } else {
  409. initialization = this.parseExpressionFromTokens( initializationTokens );
  410. }
  411. const condition = this.parseExpressionFromTokens( conditionTokens );
  412. const afterthought = this.parseExpressionFromTokens( afterthoughtTokens );
  413. const statement = new For( initialization, condition, afterthought );
  414. if ( this.getToken().str === '{' ) {
  415. this.parseBlock( statement );
  416. } else {
  417. statement.body.push( this.parseExpression() );
  418. }
  419. return statement;
  420. }
  421. parseIf() {
  422. const parseIfExpression = () => {
  423. this.readToken(); // skip 'if'
  424. const condTokens = this.readTokensUntil( ')' );
  425. return this.parseExpressionFromTokens( condTokens.slice( 1, condTokens.length - 1 ) );
  426. };
  427. const parseIfBlock = ( cond ) => {
  428. if ( this.getToken().str === '{' ) {
  429. this.parseBlock( cond );
  430. } else {
  431. cond.body.push( this.parseExpression() );
  432. }
  433. };
  434. //
  435. const conditional = new Conditional( parseIfExpression() );
  436. parseIfBlock( conditional );
  437. //
  438. let current = conditional;
  439. while ( this.getToken() && this.getToken().str === 'else' ) {
  440. this.readToken(); // skip 'else'
  441. const previous = current;
  442. if ( this.getToken().str === 'if' ) {
  443. current = new Conditional( parseIfExpression() );
  444. } else {
  445. current = new Conditional();
  446. }
  447. previous.elseConditional = current;
  448. parseIfBlock( current );
  449. }
  450. return conditional;
  451. }
  452. parseBlock( scope ) {
  453. const firstToken = this.getToken();
  454. if ( firstToken.str === '{' ) {
  455. this.readToken(); // skip '{'
  456. }
  457. let groupIndex = 0;
  458. while ( this.index < this.tokens.length ) {
  459. const token = this.getToken();
  460. let statement = null;
  461. groupIndex += getGroupDelta( token.str );
  462. if ( groupIndex < 0 ) {
  463. this.readToken(); // skip '}'
  464. break;
  465. }
  466. //
  467. if ( token.isLiteral ) {
  468. if ( token.str === 'const' ) {
  469. statement = this.parseVariables();
  470. } else if ( token.str === 'uniform' ) {
  471. statement = this.parseUniform();
  472. } else if ( token.str === 'varying' ) {
  473. statement = this.parseVarying();
  474. } else if ( isType( token.str ) ) {
  475. if ( this.getToken( 2 ).str === '(' ) {
  476. statement = this.parseFunction();
  477. } else {
  478. statement = this.parseVariables();
  479. }
  480. } else if ( token.str === 'return' ) {
  481. statement = this.parseReturn();
  482. } else if ( token.str === 'if' ) {
  483. statement = this.parseIf();
  484. } else if ( token.str === 'for' ) {
  485. statement = this.parseFor();
  486. } else {
  487. statement = this.parseExpression();
  488. }
  489. }
  490. if ( statement ) {
  491. scope.body.push( statement );
  492. } else {
  493. this.index ++;
  494. }
  495. }
  496. }
  497. _evalOperator( operator ) {
  498. if ( operator.type.includes( '=' ) ) {
  499. const parameter = this._getFunctionParameter( operator.left.property );
  500. if ( parameter !== undefined ) {
  501. // Parameters are immutable in WGSL
  502. parameter.immutable = false;
  503. }
  504. }
  505. return operator;
  506. }
  507. _getFunctionParameter( name ) {
  508. if ( this._currentFunction ) {
  509. for ( const param of this._currentFunction.params ) {
  510. if ( param.name === name ) {
  511. return param;
  512. }
  513. }
  514. }
  515. }
  516. parse( source ) {
  517. let polyfill = '';
  518. for ( const keyword of this.keywords ) {
  519. if ( new RegExp( `(^|\\b)${ keyword.name }($|\\b)`, 'gm' ).test( source ) ) {
  520. polyfill += keyword.polyfill + '\n';
  521. }
  522. }
  523. if ( polyfill ) {
  524. polyfill = '// Polyfills\n\n' + polyfill + '\n';
  525. }
  526. this.index = 0;
  527. this.tokenizer = new Tokenizer( polyfill + source ).tokenize();
  528. const program = new Program();
  529. this.parseBlock( program );
  530. return program;
  531. }
  532. }
  533. export default GLSLDecoder;