WGSLEncoder.js 18 KB

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