TSLEncoder.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933
  1. import { REVISION } from 'three/webgpu';
  2. import * as TSL from 'three/tsl';
  3. import { VariableDeclaration, Accessor } from './AST.js';
  4. import { isExpression, isPrimitive } from './TranspilerUtils.js';
  5. const opLib = {
  6. '=': 'assign',
  7. '+': 'add',
  8. '-': 'sub',
  9. '*': 'mul',
  10. '/': 'div',
  11. '%': 'remainder',
  12. '<': 'lessThan',
  13. '>': 'greaterThan',
  14. '<=': 'lessThanEqual',
  15. '>=': 'greaterThanEqual',
  16. '==': 'equal',
  17. '!=': 'notEqual',
  18. '&&': 'and',
  19. '||': 'or',
  20. '^^': 'xor',
  21. '&': 'bitAnd',
  22. '|': 'bitOr',
  23. '^': 'bitXor',
  24. '<<': 'shiftLeft',
  25. '>>': 'shiftRight',
  26. '+=': 'addAssign',
  27. '-=': 'subAssign',
  28. '*=': 'mulAssign',
  29. '/=': 'divAssign',
  30. '%=': 'remainderAssign',
  31. '^=': 'bitXorAssign',
  32. '&=': 'bitAndAssign',
  33. '|=': 'bitOrAssign',
  34. '<<=': 'shiftLeftAssign',
  35. '>>=': 'shiftRightAssign'
  36. };
  37. const unaryLib = {
  38. '+': '', // positive
  39. '-': 'negate',
  40. '~': 'bitNot',
  41. '!': 'not',
  42. '++': 'increment', // incrementBefore
  43. '--': 'decrement' // decrementBefore
  44. };
  45. const textureLookupFunctions = [ 'texture', 'texture2D', 'texture3D', 'textureCube', 'textureLod', 'texelFetch', 'textureGrad' ];
  46. class TSLEncoder {
  47. constructor() {
  48. this.tab = '';
  49. this.imports = new Set();
  50. this.global = new Set();
  51. this.overloadings = new Map();
  52. this.iife = false;
  53. this.reference = false;
  54. this.block = null;
  55. }
  56. addImport( name ) {
  57. // import only if it's a node
  58. name = name.split( '.' )[ 0 ];
  59. if ( TSL[ name ] !== undefined && this.global.has( name ) === false ) {
  60. this.imports.add( name );
  61. }
  62. }
  63. emitUniform( node ) {
  64. let code = `const ${ node.name } = `;
  65. this.global.add( node.name );
  66. if ( this.reference === true ) {
  67. this.addImport( 'reference' );
  68. //code += `reference( '${ node.name }', '${ node.type }', uniforms )`;
  69. // legacy
  70. code += `reference( 'value', '${ node.type }', uniforms[ '${ node.name }' ] )`;
  71. } else {
  72. if ( node.type === 'texture' ) {
  73. this.addImport( 'texture' );
  74. code += 'texture( /* <THREE.Texture> */ )';
  75. } else if ( node.type === 'cubeTexture' ) {
  76. this.addImport( 'cubeTexture' );
  77. code += 'cubeTexture( /* <THREE.CubeTexture> */ )';
  78. } else if ( node.type === 'texture3D' ) {
  79. this.addImport( 'texture3D' );
  80. code += 'texture3D( /* <THREE.Data3DTexture> */ )';
  81. } else {
  82. // default uniform
  83. this.addImport( 'uniform' );
  84. code += `uniform( '${ node.type }' )`;
  85. }
  86. }
  87. return code;
  88. }
  89. emitExpression( node, output = null ) {
  90. let code;
  91. if ( node.isAccessor ) {
  92. if ( node.linker.reference === null ) {
  93. this.addImport( node.property );
  94. }
  95. code = node.property;
  96. } else if ( node.isNumber ) {
  97. code = node.value;
  98. } else if ( node.isString ) {
  99. code = '\'' + node.value + '\'';
  100. } else if ( node.isOperator ) {
  101. const opFn = opLib[ node.type ] || node.type;
  102. const left = this.emitExpression( node.left, output );
  103. const right = this.emitExpression( node.right, output );
  104. if ( node.isNumericExpression ) {
  105. return left + ' ' + node.type + ' ' + right;
  106. }
  107. if ( isPrimitive( left ) ) {
  108. code = opFn + '( ' + left + ', ' + right + ' )';
  109. this.addImport( opFn );
  110. } else if ( opFn === '.' ) {
  111. code = left + opFn + right;
  112. } else {
  113. code = left + '.' + opFn + '( ' + right + ' )';
  114. }
  115. } else if ( node.isFunctionCall ) {
  116. const params = [];
  117. for ( const parameter of node.params ) {
  118. params.push( this.emitExpression( parameter ) );
  119. }
  120. // handle texture lookup function calls in separate branch
  121. if ( textureLookupFunctions.includes( node.name ) ) {
  122. code = `${ params[ 0 ] }.sample( ${ params[ 1 ] } )`;
  123. if ( node.name === 'texture' || node.name === 'texture2D' || node.name === 'texture3D' || node.name === 'textureCube' ) {
  124. if ( params.length === 3 ) {
  125. code += `.bias( ${ params[ 2 ] } )`;
  126. }
  127. } else if ( node.name === 'textureLod' ) {
  128. code += `.level( ${ params[ 2 ] } )`;
  129. } else if ( node.name === 'textureGrad' ) {
  130. code += `.grad( ${ params[ 2 ] }, ${ params[ 3 ] } )`;
  131. } else if ( node.name === 'texelFetch' ) {
  132. code += '.setSampler( false )';
  133. }
  134. } else {
  135. this.addImport( node.name );
  136. const paramsStr = params.length > 0 ? ' ' + params.join( ', ' ) + ' ' : '';
  137. code = `${ node.name }(${ paramsStr })`;
  138. }
  139. } else if ( node.isReturn ) {
  140. code = 'return';
  141. if ( node.value ) {
  142. code += ' ' + this.emitExpression( node.value );
  143. }
  144. } else if ( node.isDiscard ) {
  145. this.addImport( 'Discard' );
  146. code = 'Discard()';
  147. } else if ( node.isBreak ) {
  148. this.addImport( 'Break' );
  149. code = 'Break()';
  150. } else if ( node.isContinue ) {
  151. this.addImport( 'Continue' );
  152. code = 'Continue()';
  153. } else if ( node.isAccessorElements ) {
  154. code = this.emitExpression( node.object );
  155. for ( const element of node.elements ) {
  156. if ( element.isStaticElement ) {
  157. code += '.' + this.emitExpression( element.value );
  158. } else if ( element.isDynamicElement ) {
  159. const value = this.emitExpression( element.value );
  160. if ( isPrimitive( value ) ) {
  161. code += `[ ${ value } ]`;
  162. } else {
  163. code += `.element( ${ value } )`;
  164. }
  165. }
  166. }
  167. } else if ( node.isDynamicElement ) {
  168. code = this.emitExpression( node.value );
  169. } else if ( node.isStaticElement ) {
  170. code = this.emitExpression( node.value );
  171. } else if ( node.isFor ) {
  172. code = this.emitFor( node );
  173. } else if ( node.isWhile ) {
  174. code = this.emitWhile( node );
  175. } else if ( node.isSwitch ) {
  176. code = this.emitSwitch( node );
  177. } else if ( node.isVariableDeclaration ) {
  178. code = this.emitVariables( node );
  179. } else if ( node.isUniform ) {
  180. code = this.emitUniform( node );
  181. } else if ( node.isVarying ) {
  182. code = this.emitVarying( node );
  183. } else if ( node.isTernary ) {
  184. code = this.emitTernary( node );
  185. } else if ( node.isConditional ) {
  186. code = this.emitConditional( node );
  187. } else if ( node.isUnary && node.expression.isNumber && node.type === '-' ) {
  188. code = '- ' + node.expression.value;
  189. if ( node.expression.type !== 'float' ) {
  190. code = node.expression.type + '( ' + code + ' )';
  191. this.addImport( node.expression.type );
  192. }
  193. } else if ( node.isUnary ) {
  194. let type = unaryLib[ node.type ];
  195. if ( node.hasAssignment ) {
  196. if ( node.after === false && ( node.type === '++' || node.type === '--' ) ) {
  197. type += 'Before';
  198. }
  199. }
  200. const exp = this.emitExpression( node.expression );
  201. if ( isPrimitive( exp ) ) {
  202. this.addImport( type );
  203. code = type + '( ' + exp + ' )';
  204. } else {
  205. code = exp + '.' + type + '()';
  206. }
  207. } else {
  208. console.warn( 'Unknown node type', node );
  209. }
  210. if ( ! code ) code = '/* unknown statement */';
  211. return code;
  212. }
  213. emitBody( body ) {
  214. let code = '';
  215. this.tab += '\t';
  216. for ( const statement of body ) {
  217. code += this.emitExtraLine( statement, body );
  218. if ( statement.isComment ) {
  219. code += this.emitComment( statement, body );
  220. continue;
  221. }
  222. if ( this.block && this.block.isSwitchCase ) {
  223. if ( statement.isBreak ) continue; // skip break statements in switch cases
  224. }
  225. code += this.tab + this.emitExpression( statement );
  226. if ( code.slice( - 1 ) !== '}' ) code += ';';
  227. code += '\n';
  228. }
  229. code = code.slice( 0, - 1 ); // remove the last extra line
  230. this.tab = this.tab.slice( 0, - 1 );
  231. return code;
  232. }
  233. emitTernary( node ) {
  234. const condStr = this.emitExpression( node.cond );
  235. const leftStr = this.emitExpression( node.left );
  236. const rightStr = this.emitExpression( node.right );
  237. this.addImport( 'select' );
  238. return `select( ${ condStr }, ${ leftStr }, ${ rightStr } )`;
  239. }
  240. emitConditional( node ) {
  241. const condStr = this.emitExpression( node.cond );
  242. const bodyStr = this.emitBody( node.body );
  243. let ifStr = `If( ${ condStr }, () => {
  244. ${ bodyStr }
  245. ${ this.tab }} )`;
  246. let current = node;
  247. while ( current.elseConditional ) {
  248. const elseBodyStr = this.emitBody( current.elseConditional.body );
  249. if ( current.elseConditional.cond ) {
  250. const elseCondStr = this.emitExpression( current.elseConditional.cond );
  251. ifStr += `.ElseIf( ${ elseCondStr }, () => {
  252. ${ elseBodyStr }
  253. ${ this.tab }} )`;
  254. } else {
  255. ifStr += `.Else( () => {
  256. ${ elseBodyStr }
  257. ${ this.tab }} )`;
  258. }
  259. current = current.elseConditional;
  260. }
  261. this.imports.add( 'If' );
  262. return ifStr;
  263. }
  264. emitLoop( node ) {
  265. const start = this.emitExpression( node.initialization.value );
  266. const end = this.emitExpression( node.condition.right );
  267. const name = node.initialization.name;
  268. const type = node.initialization.type;
  269. const condition = node.condition.type;
  270. const nameParam = name !== 'i' ? `, name: '${ name }'` : '';
  271. const typeParam = type !== 'int' ? `, type: '${ type }'` : '';
  272. const conditionParam = condition !== '<' ? `, condition: '${ condition }'` : '';
  273. let updateParam = '';
  274. if ( node.afterthought.isUnary ) {
  275. if ( node.afterthought.type !== '++' ) {
  276. updateParam = `, update: '${ node.afterthought.type }'`;
  277. }
  278. } else if ( node.afterthought.isOperator ) {
  279. if ( node.afterthought.right.isAccessor || node.afterthought.right.isNumber ) {
  280. updateParam = `, update: ${ this.emitExpression( node.afterthought.right ) }`;
  281. } else {
  282. updateParam = `, update: ( { i } ) => ${ this.emitExpression( node.afterthought ) }`;
  283. }
  284. }
  285. let loopStr = `Loop( { start: ${ start }, end: ${ end + nameParam + typeParam + conditionParam + updateParam } }, ( { ${ name } } ) => {\n\n`;
  286. loopStr += this.emitBody( node.body ) + '\n\n';
  287. loopStr += this.tab + '} )';
  288. this.imports.add( 'Loop' );
  289. return loopStr;
  290. }
  291. emitSwitch( switchNode ) {
  292. const discriminantString = this.emitExpression( switchNode.discriminant );
  293. this.tab += '\t';
  294. let switchString = `Switch( ${ discriminantString } )\n${ this.tab }`;
  295. const previousBlock = this.block;
  296. for ( const switchCase of switchNode.cases ) {
  297. this.block = switchCase;
  298. let caseBodyString;
  299. if ( ! switchCase.isDefault ) {
  300. const caseConditions = [ ];
  301. for ( const condition of switchCase.conditions ) {
  302. caseConditions.push( this.emitExpression( condition ) );
  303. }
  304. caseBodyString = this.emitBody( switchCase.body );
  305. switchString += `.Case( ${ caseConditions.join( ', ' ) }, `;
  306. } else {
  307. caseBodyString = this.emitBody( switchCase.body );
  308. switchString += '.Default( ';
  309. }
  310. switchString += `() => {
  311. ${ caseBodyString }
  312. ${ this.tab }} )`;
  313. }
  314. this.block = previousBlock;
  315. this.tab = this.tab.slice( 0, - 1 );
  316. this.imports.add( 'Switch' );
  317. return switchString;
  318. }
  319. emitFor( node ) {
  320. const { initialization, condition, afterthought } = node;
  321. if ( ( initialization && initialization.isVariableDeclaration && initialization.next === null ) &&
  322. ( condition && condition.left.isAccessor && condition.left.property === initialization.name ) &&
  323. ( afterthought && (
  324. ( afterthought.isUnary && ( initialization.name === afterthought.expression.property ) ) ||
  325. ( afterthought.isOperator && ( initialization.name === afterthought.left.property ) )
  326. ) )
  327. ) {
  328. return this.emitLoop( node );
  329. }
  330. return this.emitForWhile( node );
  331. }
  332. emitForWhile( node ) {
  333. const initialization = this.emitExpression( node.initialization );
  334. const condition = this.emitExpression( node.condition );
  335. const afterthought = this.emitExpression( node.afterthought );
  336. this.tab += '\t';
  337. let forStr = '{\n\n' + this.tab + initialization + ';\n\n';
  338. forStr += `${ this.tab }Loop( ${ condition }, () => {\n\n`;
  339. forStr += this.emitBody( node.body ) + '\n\n';
  340. forStr += this.tab + '\t' + afterthought + ';\n\n';
  341. forStr += this.tab + '} )\n\n';
  342. this.tab = this.tab.slice( 0, - 1 );
  343. forStr += this.tab + '}';
  344. this.imports.add( 'Loop' );
  345. return forStr;
  346. }
  347. emitWhile( node ) {
  348. const condition = this.emitExpression( node.condition );
  349. let whileStr = `Loop( ${ condition }, () => {\n\n`;
  350. whileStr += this.emitBody( node.body ) + '\n\n';
  351. whileStr += this.tab + '} )';
  352. this.imports.add( 'Loop' );
  353. return whileStr;
  354. }
  355. emitVariables( node, isRoot = true ) {
  356. const { name, type, value, next } = node;
  357. let varStr = isRoot ? 'const ' : '';
  358. varStr += name;
  359. if ( value ) {
  360. let valueStr = this.emitExpression( value );
  361. if ( value.isNumericExpression ) {
  362. // convert JS primitive to node
  363. valueStr = `${ type }( ${ valueStr } )`;
  364. this.addImport( type );
  365. }
  366. varStr += ' = ' + valueStr;
  367. } else {
  368. varStr += ` = property( '${ type }' )`;
  369. this.addImport( 'property' );
  370. }
  371. if ( next ) {
  372. varStr += ', ' + this.emitVariables( next, false );
  373. }
  374. return varStr;
  375. }
  376. emitVarying( node ) {
  377. const { name, type } = node;
  378. this.addImport( 'varying' );
  379. this.addImport( type );
  380. return `const ${ name } = varying( ${ type }(), '${ name }' )`;
  381. }
  382. emitOverloadingFunction( nodes ) {
  383. const { name } = nodes[ 0 ];
  384. this.addImport( 'overloadingFn' );
  385. const prefix = this.iife === false ? 'export ' : '';
  386. return `${ prefix }const ${ name } = /*@__PURE__*/ overloadingFn( [ ${ nodes.map( node => node.name + '_' + nodes.indexOf( node ) ).join( ', ' ) } ] );\n`;
  387. }
  388. emitFunction( node ) {
  389. const { name, type } = node;
  390. const params = [];
  391. const inputs = [];
  392. const mutableParams = [];
  393. let hasPointer = false;
  394. for ( const param of node.params ) {
  395. let name = param.name;
  396. if ( param.linker.assignments.length > 0 ) {
  397. name = name + '_immutable';
  398. mutableParams.push( param );
  399. }
  400. if ( param.qualifier ) {
  401. if ( param.qualifier === 'inout' || param.qualifier === 'out' ) {
  402. hasPointer = true;
  403. }
  404. }
  405. inputs.push( param.name + ': \'' + param.type + '\'' );
  406. params.push( name );
  407. }
  408. for ( const param of mutableParams ) {
  409. const mutableParam = new VariableDeclaration( param.type, param.name, new Accessor( param.name + '_immutable' ), null, true );
  410. mutableParam.parent = param.parent; // link to the original node
  411. mutableParam.linker.assignments.push( mutableParam );
  412. node.body.unshift( mutableParam );
  413. }
  414. const paramsStr = params.length > 0 ? ' [ ' + params.join( ', ' ) + ' ] ' : '';
  415. const bodyStr = this.emitBody( node.body );
  416. let fnName = name;
  417. let overloadingNodes = null;
  418. if ( this.overloadings.has( name ) ) {
  419. const overloadings = this.overloadings.get( name );
  420. if ( overloadings.length > 1 ) {
  421. const index = overloadings.indexOf( node );
  422. fnName += '_' + index;
  423. if ( index === overloadings.length - 1 ) {
  424. overloadingNodes = overloadings;
  425. }
  426. }
  427. }
  428. const prefix = this.iife === false ? 'export ' : '';
  429. let funcStr = `${ prefix }const ${ fnName } = /*@__PURE__*/ Fn( (${ paramsStr }) => {
  430. ${ bodyStr }
  431. ${ this.tab }}`;
  432. if ( node.layout !== false && hasPointer === false ) {
  433. funcStr += ', { ' + inputs.join( ', ' ) + ', return: \'' + type + '\' }';
  434. }
  435. funcStr += ' );\n';
  436. this.imports.add( 'Fn' );
  437. this.global.add( node.name );
  438. if ( overloadingNodes !== null ) {
  439. funcStr += '\n' + this.emitOverloadingFunction( overloadingNodes );
  440. }
  441. return funcStr;
  442. }
  443. emitComment( statement, body ) {
  444. const index = body.indexOf( statement );
  445. const previous = body[ index - 1 ];
  446. const next = body[ index + 1 ];
  447. let output = '';
  448. if ( previous && isExpression( previous ) ) {
  449. output += '\n';
  450. }
  451. output += this.tab + statement.comment.replace( /\n/g, '\n' + this.tab ) + '\n';
  452. if ( next && isExpression( next ) ) {
  453. output += '\n';
  454. }
  455. return output;
  456. }
  457. emitExtraLine( statement, body ) {
  458. const index = body.indexOf( statement );
  459. const previous = body[ index - 1 ];
  460. if ( previous === undefined ) return '';
  461. if ( statement.isReturn ) return '\n';
  462. const lastExp = isExpression( previous );
  463. const currExp = isExpression( statement );
  464. if ( lastExp !== currExp || ( ! lastExp && ! currExp ) ) return '\n';
  465. return '';
  466. }
  467. emit( ast ) {
  468. let code = '\n';
  469. if ( this.iife ) this.tab += '\t';
  470. const overloadings = this.overloadings;
  471. for ( const statement of ast.body ) {
  472. if ( statement.isFunctionDeclaration ) {
  473. if ( overloadings.has( statement.name ) === false ) {
  474. overloadings.set( statement.name, [] );
  475. }
  476. overloadings.get( statement.name ).push( statement );
  477. }
  478. }
  479. for ( const statement of ast.body ) {
  480. code += this.emitExtraLine( statement, ast.body );
  481. if ( statement.isComment ) {
  482. code += this.emitComment( statement, ast.body );
  483. continue;
  484. }
  485. if ( statement.isFunctionDeclaration ) {
  486. code += this.tab + this.emitFunction( statement );
  487. } else {
  488. code += this.tab + this.emitExpression( statement ) + ';\n';
  489. }
  490. }
  491. const imports = [ ...this.imports ];
  492. const exports = [ ...this.global ];
  493. let header = '// Three.js Transpiler r' + REVISION + '\n\n';
  494. let footer = '';
  495. if ( this.iife ) {
  496. header += '( function ( TSL, uniforms ) {\n\n';
  497. header += imports.length > 0 ? '\tconst { ' + imports.join( ', ' ) + ' } = TSL;\n' : '';
  498. footer += exports.length > 0 ? '\treturn { ' + exports.join( ', ' ) + ' };\n' : '';
  499. footer += '\n} );';
  500. } else {
  501. header += imports.length > 0 ? 'import { ' + imports.join( ', ' ) + ' } from \'three/tsl\';\n' : '';
  502. }
  503. return header + code + footer;
  504. }
  505. }
  506. export default TSLEncoder;
粤ICP备19079148号