WGSLEncoder.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788
  1. import { REVISION } from 'three/webgpu';
  2. import { VariableDeclaration, Accessor } from './AST.js';
  3. import { isExpression } from './TranspilerUtils.js';
  4. // Note: This is a simplified list. A complete implementation would need more mappings.
  5. const typeMap = {
  6. 'float': 'f32',
  7. 'int': 'i32',
  8. 'uint': 'u32',
  9. 'bool': 'bool',
  10. 'vec2': 'vec2f',
  11. 'ivec2': 'vec2i',
  12. 'uvec2': 'vec2u',
  13. 'bvec2': 'vec2b',
  14. 'vec3': 'vec3f',
  15. 'ivec3': 'vec3i',
  16. 'uvec3': 'vec3u',
  17. 'bvec3': 'vec3b',
  18. 'vec4': 'vec4f',
  19. 'ivec4': 'vec4i',
  20. 'uvec4': 'vec4u',
  21. 'bvec4': 'vec4b',
  22. 'mat3': 'mat3x3<f32>',
  23. 'mat4': 'mat4x4<f32>',
  24. 'texture': 'texture_2d<f32>',
  25. 'textureCube': 'texture_cube<f32>',
  26. 'texture3D': 'texture_3d<f32>',
  27. };
  28. // GLSL to WGSL built-in function mapping
  29. const wgslLib = {
  30. 'abs': 'abs',
  31. 'acos': 'acos',
  32. 'asin': 'asin',
  33. 'atan': 'atan',
  34. 'atan2': 'atan2',
  35. 'ceil': 'ceil',
  36. 'clamp': 'clamp',
  37. 'cos': 'cos',
  38. 'cross': 'cross',
  39. 'degrees': 'degrees',
  40. 'distance': 'distance',
  41. 'dot': 'dot',
  42. 'exp': 'exp',
  43. 'exp2': 'exp2',
  44. 'faceforward': 'faceForward',
  45. 'floor': 'floor',
  46. 'fract': 'fract',
  47. 'inverse': 'inverse',
  48. 'inversesqrt': 'inverseSqrt',
  49. 'length': 'length',
  50. 'log': 'log',
  51. 'log2': 'log2',
  52. 'max': 'max',
  53. 'min': 'min',
  54. 'mix': 'mix',
  55. 'normalize': 'normalize',
  56. 'pow': 'pow',
  57. 'radians': 'radians',
  58. 'reflect': 'reflect',
  59. 'refract': 'refract',
  60. 'round': 'round',
  61. 'sign': 'sign',
  62. 'sin': 'sin',
  63. 'smoothstep': 'smoothstep',
  64. 'sqrt': 'sqrt',
  65. 'step': 'step',
  66. 'tan': 'tan',
  67. 'transpose': 'transpose',
  68. 'trunc': 'trunc',
  69. 'dFdx': 'dpdx',
  70. 'dFdy': 'dpdy',
  71. 'fwidth': 'fwidth',
  72. // Texture functions are handled separately
  73. 'texture': 'textureSample',
  74. 'texture2D': 'textureSample',
  75. 'texture3D': 'textureSample',
  76. 'textureCube': 'textureSample',
  77. 'textureLod': 'textureSampleLevel',
  78. 'texelFetch': 'textureLoad',
  79. 'textureGrad': 'textureSampleGrad',
  80. };
  81. class WGSLEncoder {
  82. constructor() {
  83. this.tab = '';
  84. this.functions = new Map();
  85. this.uniforms = [];
  86. this.varyings = [];
  87. this.structs = new Map();
  88. this.polyfills = new Map();
  89. // Assume a single group for simplicity
  90. this.groupIndex = 0;
  91. }
  92. getWgslType( type ) {
  93. return typeMap[ type ] || type;
  94. }
  95. emitExpression( node ) {
  96. if ( ! node ) return '';
  97. let code;
  98. if ( node.isAccessor ) {
  99. // Check if this accessor is part of a uniform struct
  100. const uniform = this.uniforms.find( u => u.name === node.property );
  101. if ( uniform && ! uniform.type.includes( 'texture' ) ) {
  102. return `uniforms.${node.property}`;
  103. }
  104. code = node.property;
  105. } else if ( node.isNumber ) {
  106. code = node.value;
  107. // WGSL requires floating point numbers to have a decimal
  108. if ( node.type === 'float' && ! code.includes( '.' ) ) {
  109. code += '.0';
  110. }
  111. } else if ( node.isOperator ) {
  112. const left = this.emitExpression( node.left );
  113. const right = this.emitExpression( node.right );
  114. code = `${ left } ${ node.type } ${ right }`;
  115. if ( node.parent.isAssignment !== true && node.parent.isOperator ) {
  116. code = `( ${ code } )`;
  117. }
  118. } else if ( node.isFunctionCall ) {
  119. const fnName = wgslLib[ node.name ] || node.name;
  120. if ( fnName === 'mod' ) {
  121. const snippets = node.params.map( p => this.emitExpression( p ) );
  122. const types = node.params.map( p => p.getType() );
  123. const modFnName = 'mod_' + types.join( '_' );
  124. if ( this.polyfills.has( modFnName ) === false ) {
  125. this.polyfills.set( modFnName, `fn ${ modFnName }( x: ${ this.getWgslType( types[ 0 ] ) }, y: ${ this.getWgslType( types[ 1 ] ) } ) -> ${ this.getWgslType( types[ 0 ] ) } {
  126. return x - y * floor( x / y );
  127. }` );
  128. }
  129. code = `${ modFnName }( ${ snippets.join( ', ' ) } )`;
  130. } else if ( fnName.startsWith( 'texture' ) ) {
  131. // Handle texture functions separately due to sampler handling
  132. code = this.emitTextureAccess( node );
  133. } else {
  134. const params = node.params.map( p => this.emitExpression( p ) );
  135. if ( typeMap[ fnName ] ) {
  136. // Handle type constructors like vec3(...)
  137. code = this.getWgslType( fnName );
  138. } else {
  139. code = fnName;
  140. }
  141. if ( params.length > 0 ) {
  142. code += '( ' + params.join( ', ' ) + ' )';
  143. } else {
  144. code += '()';
  145. }
  146. }
  147. } else if ( node.isReturn ) {
  148. code = 'return';
  149. if ( node.value ) {
  150. code += ' ' + this.emitExpression( node.value );
  151. }
  152. } else if ( node.isDiscard ) {
  153. code = 'discard';
  154. } else if ( node.isBreak ) {
  155. if ( node.parent.isSwitchCase !== true ) {
  156. code = 'break';
  157. }
  158. } else if ( node.isContinue ) {
  159. code = 'continue';
  160. } else if ( node.isAccessorElements ) {
  161. code = this.emitExpression( node.object );
  162. for ( const element of node.elements ) {
  163. const value = this.emitExpression( element.value );
  164. if ( element.isStaticElement ) {
  165. code += '.' + value;
  166. } else if ( element.isDynamicElement ) {
  167. code += `[${value}]`;
  168. }
  169. }
  170. } else if ( node.isFor ) {
  171. code = this.emitFor( node );
  172. } else if ( node.isWhile ) {
  173. code = this.emitWhile( node );
  174. } else if ( node.isSwitch ) {
  175. code = this.emitSwitch( node );
  176. } else if ( node.isVariableDeclaration ) {
  177. code = this.emitVariables( node );
  178. } else if ( node.isUniform ) {
  179. this.uniforms.push( node );
  180. return ''; // Defer emission to the header
  181. } else if ( node.isVarying ) {
  182. this.varyings.push( node );
  183. return ''; // Defer emission to the header
  184. } else if ( node.isTernary ) {
  185. const cond = this.emitExpression( node.cond );
  186. const left = this.emitExpression( node.left );
  187. const right = this.emitExpression( node.right );
  188. // WGSL's equivalent to the ternary operator is select(false_val, true_val, condition)
  189. code = `select( ${ right }, ${ left }, ${ cond } )`;
  190. } else if ( node.isConditional ) {
  191. code = this.emitConditional( node );
  192. } else if ( node.isUnary ) {
  193. const expr = this.emitExpression( node.expression );
  194. if ( node.type === '++' || node.type === '--' ) {
  195. const op = node.type === '++' ? '+' : '-';
  196. code = `${ expr } = ${ expr } ${ op } 1`;
  197. } else {
  198. code = `${ node.type }${ expr }`;
  199. }
  200. } else {
  201. console.warn( 'Unknown node type in WGSL Encoder:', node );
  202. code = `/* unknown node: ${ node.constructor.name } */`;
  203. }
  204. return code;
  205. }
  206. emitTextureAccess( node ) {
  207. const wgslFn = wgslLib[ node.name ];
  208. const textureName = this.emitExpression( node.params[ 0 ] );
  209. const uv = this.emitExpression( node.params[ 1 ] );
  210. // WGSL requires explicit samplers. We assume a naming convention.
  211. const samplerName = `${textureName}_sampler`;
  212. let code;
  213. switch ( node.name ) {
  214. case 'texture':
  215. case 'texture2D':
  216. case 'texture3D':
  217. case 'textureCube':
  218. // format: textureSample(texture, sampler, coords, [offset])
  219. code = `${wgslFn}(${textureName}, ${samplerName}, ${uv}`;
  220. // Handle optional bias parameter (note: WGSL uses textureSampleBias)
  221. if ( node.params.length === 3 ) {
  222. const bias = this.emitExpression( node.params[ 2 ] );
  223. code = `textureSampleBias(${textureName}, ${samplerName}, ${uv}, ${bias})`;
  224. } else {
  225. code += ')';
  226. }
  227. break;
  228. case 'textureLod':
  229. // format: textureSampleLevel(texture, sampler, coords, level)
  230. const lod = this.emitExpression( node.params[ 2 ] );
  231. code = `${wgslFn}(${textureName}, ${samplerName}, ${uv}, ${lod})`;
  232. break;
  233. case 'textureGrad':
  234. // format: textureSampleGrad(texture, sampler, coords, ddx, ddy)
  235. const ddx = this.emitExpression( node.params[ 2 ] );
  236. const ddy = this.emitExpression( node.params[ 3 ] );
  237. code = `${wgslFn}(${textureName}, ${samplerName}, ${uv}, ${ddx}, ${ddy})`;
  238. break;
  239. case 'texelFetch':
  240. // format: textureLoad(texture, coords, [level])
  241. const coords = this.emitExpression( node.params[ 1 ] ); // should be ivec
  242. const lodFetch = node.params.length > 2 ? this.emitExpression( node.params[ 2 ] ) : '0';
  243. code = `${wgslFn}(${textureName}, ${coords}, ${lodFetch})`;
  244. break;
  245. default:
  246. code = `/* unsupported texture op: ${node.name} */`;
  247. }
  248. return code;
  249. }
  250. emitBody( body ) {
  251. let code = '';
  252. this.tab += '\t';
  253. for ( const statement of body ) {
  254. code += this.emitExtraLine( statement, body );
  255. if ( statement.isComment ) {
  256. code += this.emitComment( statement, body );
  257. continue;
  258. }
  259. const statementCode = this.emitExpression( statement );
  260. if ( statementCode ) {
  261. code += this.tab + statementCode;
  262. if ( ! statementCode.endsWith( '}' ) && ! statementCode.endsWith( '{' ) ) {
  263. code += ';';
  264. }
  265. code += '\n';
  266. }
  267. }
  268. this.tab = this.tab.slice( 0, - 1 );
  269. return code.slice( 0, - 1 ); // remove the last extra line
  270. }
  271. emitConditional( node ) {
  272. const condStr = this.emitExpression( node.cond );
  273. const bodyStr = this.emitBody( node.body );
  274. let ifStr = `if ( ${ condStr } ) {\n\n${ bodyStr }\n\n${ this.tab }}`;
  275. let current = node;
  276. while ( current.elseConditional ) {
  277. current = current.elseConditional;
  278. const elseBodyStr = this.emitBody( current.body );
  279. if ( current.cond ) { // This is an 'else if'
  280. const elseCondStr = this.emitExpression( current.cond );
  281. ifStr += ` else if ( ${ elseCondStr } ) {\n\n${ elseBodyStr }\n\n${ this.tab }}`;
  282. } else { // This is an 'else'
  283. ifStr += ` else {\n\n${ elseBodyStr }\n\n${ this.tab }}`;
  284. }
  285. }
  286. return ifStr;
  287. }
  288. emitFor( node ) {
  289. const init = this.emitExpression( node.initialization );
  290. const cond = this.emitExpression( node.condition );
  291. const after = this.emitExpression( node.afterthought );
  292. const body = this.emitBody( node.body );
  293. return `for ( ${ init }; ${ cond }; ${ after } ) {\n\n${ body }\n\n${ this.tab }}`;
  294. }
  295. emitWhile( node ) {
  296. const cond = this.emitExpression( node.condition );
  297. const body = this.emitBody( node.body );
  298. return `while ( ${ cond } ) {\n\n${ body }\n\n${ this.tab }}`;
  299. }
  300. emitSwitch( node ) {
  301. const discriminant = this.emitExpression( node.discriminant );
  302. let switchStr = `switch ( ${ discriminant } ) {\n\n`;
  303. this.tab += '\t';
  304. for ( const switchCase of node.cases ) {
  305. const body = this.emitBody( switchCase.body );
  306. if ( switchCase.isDefault ) {
  307. switchStr += `${ this.tab }default: {\n\n${ body }\n\n${ this.tab }}\n\n`;
  308. } else {
  309. const cases = switchCase.conditions.map( c => this.emitExpression( c ) ).join( ', ' );
  310. switchStr += `${ this.tab }case ${ cases }: {\n\n${ body }\n\n${ this.tab }}\n\n`;
  311. }
  312. }
  313. this.tab = this.tab.slice( 0, - 1 );
  314. switchStr += `${this.tab}}`;
  315. return switchStr;
  316. }
  317. emitVariables( node ) {
  318. const declarations = [];
  319. let current = node;
  320. while ( current ) {
  321. const type = this.getWgslType( current.type );
  322. let valueStr = '';
  323. if ( current.value ) {
  324. valueStr = ` = ${this.emitExpression( current.value )}`;
  325. }
  326. // The AST linker tracks if a variable is ever reassigned.
  327. // If so, use 'var'; otherwise, use 'let'.
  328. let keyword;
  329. if ( current.linker ) {
  330. if ( current.linker.assignments.length > 0 ) {
  331. keyword = 'var'; // Reassigned variable
  332. } else {
  333. if ( current.value && current.value.isNumericExpression ) {
  334. keyword = 'const'; // Immutable numeric expression
  335. } else {
  336. keyword = 'let'; // Immutable variable
  337. }
  338. }
  339. }
  340. declarations.push( `${ keyword } ${ current.name }: ${ type }${ valueStr }` );
  341. current = current.next;
  342. }
  343. // In WGSL, multiple declarations in one line are not supported, so join with semicolons.
  344. return declarations.join( ';\n' + this.tab );
  345. }
  346. emitFunction( node ) {
  347. const name = node.name;
  348. const returnType = this.getWgslType( node.type );
  349. const params = [];
  350. // We will prepend to a copy of the body, not the original AST node.
  351. const body = [ ...node.body ];
  352. for ( const param of node.params ) {
  353. const paramName = param.name;
  354. let paramType = this.getWgslType( param.type );
  355. // Handle 'inout' and 'out' qualifiers using pointers. They are already mutable.
  356. if ( param.qualifier === 'inout' || param.qualifier === 'out' ) {
  357. paramType = `ptr<function, ${paramType}>`;
  358. params.push( `${paramName}: ${paramType}` );
  359. continue;
  360. }
  361. // If the parameter is reassigned within the function, we need to
  362. // create a local, mutable variable that shadows the parameter's name.
  363. if ( param.linker && param.linker.assignments.length > 0 ) {
  364. // 1. Rename the incoming parameter to avoid name collision.
  365. const immutableParamName = `${paramName}_in`;
  366. params.push( `${immutableParamName}: ${paramType}` );
  367. // 2. Create a new Accessor node for the renamed immutable parameter.
  368. const immutableAccessor = new Accessor( immutableParamName );
  369. immutableAccessor.isAccessor = true;
  370. immutableAccessor.property = immutableParamName;
  371. // 3. Create a new VariableDeclaration node for the mutable local variable.
  372. // This new variable will have the original parameter's name.
  373. const mutableVar = new VariableDeclaration( param.type, param.name, immutableAccessor );
  374. // 4. Mark this new variable as mutable so `emitVariables` uses `var`.
  375. mutableVar.linker = { assignments: [ true ] };
  376. // 5. Prepend this new declaration to the function's body.
  377. body.unshift( mutableVar );
  378. } else {
  379. // This parameter is not reassigned, so treat it as a normal immutable parameter.
  380. params.push( `${paramName}: ${paramType}` );
  381. }
  382. }
  383. const paramsStr = params.length > 0 ? ' ' + params.join( ', ' ) + ' ' : '';
  384. const returnStr = ( returnType && returnType !== 'void' ) ? ` -> ${returnType}` : '';
  385. // Emit the function body, which now includes our injected variable declarations.
  386. const bodyStr = this.emitBody( body );
  387. return `fn ${name}(${paramsStr})${returnStr} {\n\n${bodyStr}\n\n${this.tab}}`;
  388. }
  389. emitComment( statement, body ) {
  390. const index = body.indexOf( statement );
  391. const previous = body[ index - 1 ];
  392. const next = body[ index + 1 ];
  393. let output = '';
  394. if ( previous && isExpression( previous ) ) {
  395. output += '\n';
  396. }
  397. output += this.tab + statement.comment.replace( /\n/g, '\n' + this.tab ) + '\n';
  398. if ( next && isExpression( next ) ) {
  399. output += '\n';
  400. }
  401. return output;
  402. }
  403. emitExtraLine( statement, body ) {
  404. const index = body.indexOf( statement );
  405. const previous = body[ index - 1 ];
  406. if ( previous === undefined ) return '';
  407. if ( statement.isReturn ) return '\n';
  408. const lastExp = isExpression( previous );
  409. const currExp = isExpression( statement );
  410. if ( lastExp !== currExp || ( ! lastExp && ! currExp ) ) return '\n';
  411. return '';
  412. }
  413. emit( ast ) {
  414. const header = '// Three.js Transpiler r' + REVISION + '\n\n';
  415. let globals = '';
  416. let functions = '';
  417. let dependencies = '';
  418. // 1. Pre-process to find all global declarations
  419. for ( const statement of ast.body ) {
  420. if ( statement.isFunctionDeclaration ) {
  421. this.functions.set( statement.name, statement );
  422. } else if ( statement.isUniform ) {
  423. this.uniforms.push( statement );
  424. } else if ( statement.isVarying ) {
  425. this.varyings.push( statement );
  426. }
  427. }
  428. // 2. Build resource bindings (uniforms, textures, samplers)
  429. if ( this.uniforms.length > 0 ) {
  430. let bindingIndex = 0;
  431. const uniformStructMembers = [];
  432. const textureGlobals = [];
  433. for ( const uniform of this.uniforms ) {
  434. // Textures are declared as separate global variables, not in the UBO
  435. if ( uniform.type.includes( 'texture' ) ) {
  436. textureGlobals.push( `@group(${this.groupIndex}) @binding(${bindingIndex ++}) var ${uniform.name}: ${this.getWgslType( uniform.type )};` );
  437. textureGlobals.push( `@group(${this.groupIndex}) @binding(${bindingIndex ++}) var ${uniform.name}_sampler: sampler;` );
  438. } else {
  439. uniformStructMembers.push( `\t${uniform.name}: ${this.getWgslType( uniform.type )},` );
  440. }
  441. }
  442. // Create a UBO struct if there are any non-texture uniforms
  443. if ( uniformStructMembers.length > 0 ) {
  444. globals += 'struct Uniforms {\n';
  445. globals += uniformStructMembers.join( '\n' );
  446. globals += '\n};\n';
  447. globals += `@group(${this.groupIndex}) @binding(${bindingIndex ++}) var<uniform> uniforms: Uniforms;\n\n`;
  448. }
  449. // Add the texture and sampler globals
  450. globals += textureGlobals.join( '\n' ) + '\n\n';
  451. }
  452. // 3. Build varying structs for stage I/O
  453. // This is a simplification; a full implementation would need to know the shader stage.
  454. if ( this.varyings.length > 0 ) {
  455. globals += 'struct Varyings {\n';
  456. let location = 0;
  457. for ( const varying of this.varyings ) {
  458. globals += `\t@location(${location ++}) ${varying.name}: ${this.getWgslType( varying.type )},\n`;
  459. }
  460. globals += '};\n\n';
  461. }
  462. // 4. Emit all functions and other global statements
  463. for ( const statement of ast.body ) {
  464. functions += this.emitExtraLine( statement, ast.body );
  465. if ( statement.isFunctionDeclaration ) {
  466. functions += this.emitFunction( statement ) + '\n';
  467. } else if ( statement.isComment ) {
  468. functions += this.emitComment( statement, ast.body );
  469. } else if ( ! statement.isUniform && ! statement.isVarying ) {
  470. // Handle other top-level statements like 'const'
  471. functions += this.emitExpression( statement ) + ';\n';
  472. }
  473. }
  474. // 4. Build dependencies
  475. for ( const value of this.polyfills.values() ) {
  476. dependencies = `${ value }\n\n`;
  477. }
  478. return header + dependencies + globals + functions.trimEnd() + '\n';
  479. }
  480. }
  481. export default WGSLEncoder;
粤ICP备19079148号