WGSLNodeBuilder.js 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291
  1. import NodeUniformsGroup from '../../common/nodes/NodeUniformsGroup.js';
  2. import NodeSampler from '../../common/nodes/NodeSampler.js';
  3. import { NodeSampledTexture, NodeSampledCubeTexture, NodeSampledTexture3D } from '../../common/nodes/NodeSampledTexture.js';
  4. import NodeUniformBuffer from '../../common/nodes/NodeUniformBuffer.js';
  5. import NodeStorageBuffer from '../../common/nodes/NodeStorageBuffer.js';
  6. import { NodeBuilder, CodeNode } from '../../../nodes/Nodes.js';
  7. import { getFormat } from '../utils/WebGPUTextureUtils.js';
  8. import WGSLNodeParser from './WGSLNodeParser.js';
  9. import { NodeAccess } from '../../../nodes/core/constants.js';
  10. import VarNode from '../../../nodes/core/VarNode.js';
  11. import ExpressionNode from '../../../nodes/code/ExpressionNode.js';
  12. import { FloatType, RepeatWrapping, ClampToEdgeWrapping, MirroredRepeatWrapping, NearestFilter } from '../../../constants.js';
  13. import { warn, error } from '../../../utils.js';
  14. import { GPUShaderStage } from '../utils/WebGPUConstants.js';
  15. const accessNames = {
  16. [ NodeAccess.READ_ONLY ]: 'read',
  17. [ NodeAccess.WRITE_ONLY ]: 'write',
  18. [ NodeAccess.READ_WRITE ]: 'read_write'
  19. };
  20. const wrapNames = {
  21. [ RepeatWrapping ]: 'repeat',
  22. [ ClampToEdgeWrapping ]: 'clamp',
  23. [ MirroredRepeatWrapping ]: 'mirror'
  24. };
  25. const gpuShaderStageLib = {
  26. 'vertex': GPUShaderStage.VERTEX,
  27. 'fragment': GPUShaderStage.FRAGMENT,
  28. 'compute': GPUShaderStage.COMPUTE
  29. };
  30. const supports = {
  31. instance: true,
  32. swizzleAssign: false,
  33. storageBuffer: true
  34. };
  35. const wgslFnOpLib = {
  36. '^^': 'tsl_xor'
  37. };
  38. const wgslTypeLib = {
  39. float: 'f32',
  40. int: 'i32',
  41. uint: 'u32',
  42. bool: 'bool',
  43. color: 'vec3<f32>',
  44. vec2: 'vec2<f32>',
  45. ivec2: 'vec2<i32>',
  46. uvec2: 'vec2<u32>',
  47. bvec2: 'vec2<bool>',
  48. vec3: 'vec3<f32>',
  49. ivec3: 'vec3<i32>',
  50. uvec3: 'vec3<u32>',
  51. bvec3: 'vec3<bool>',
  52. vec4: 'vec4<f32>',
  53. ivec4: 'vec4<i32>',
  54. uvec4: 'vec4<u32>',
  55. bvec4: 'vec4<bool>',
  56. mat2: 'mat2x2<f32>',
  57. mat3: 'mat3x3<f32>',
  58. mat4: 'mat4x4<f32>'
  59. };
  60. const wgslCodeCache = {};
  61. const wgslPolyfill = {
  62. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  63. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  64. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  65. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  66. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  67. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  68. equals_bvec2: new CodeNode( 'fn tsl_equals_bvec2( a : vec2f, b : vec2f ) -> vec2<bool> { return vec2<bool>( a.x == b.x, a.y == b.y ); }' ),
  69. equals_bvec3: new CodeNode( 'fn tsl_equals_bvec3( a : vec3f, b : vec3f ) -> vec3<bool> { return vec3<bool>( a.x == b.x, a.y == b.y, a.z == b.z ); }' ),
  70. equals_bvec4: new CodeNode( 'fn tsl_equals_bvec4( a : vec4f, b : vec4f ) -> vec4<bool> { return vec4<bool>( a.x == b.x, a.y == b.y, a.z == b.z, a.w == b.w ); }' ),
  71. repeatWrapping_float: new CodeNode( 'fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }' ),
  72. mirrorWrapping_float: new CodeNode( 'fn tsl_mirrorWrapping_float( coord: f32 ) -> f32 { let mirrored = fract( coord * 0.5 ) * 2.0; return 1.0 - abs( 1.0 - mirrored ); }' ),
  73. clampWrapping_float: new CodeNode( 'fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }' ),
  74. biquadraticTexture: new CodeNode( /* wgsl */`
  75. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {
  76. let res = vec2f( iRes );
  77. let uvScaled = coord * res;
  78. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  79. // https://www.shadertoy.com/view/WtyXRy
  80. let uv = uvWrapping - 0.5;
  81. let iuv = floor( uv );
  82. let f = fract( uv );
  83. let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
  84. let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
  85. let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
  86. let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
  87. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  88. }
  89. ` )
  90. };
  91. const wgslMethods = {
  92. dFdx: 'dpdx',
  93. dFdy: '- dpdy',
  94. mod_float: 'tsl_mod_float',
  95. mod_vec2: 'tsl_mod_vec2',
  96. mod_vec3: 'tsl_mod_vec3',
  97. mod_vec4: 'tsl_mod_vec4',
  98. equals_bool: 'tsl_equals_bool',
  99. equals_bvec2: 'tsl_equals_bvec2',
  100. equals_bvec3: 'tsl_equals_bvec3',
  101. equals_bvec4: 'tsl_equals_bvec4',
  102. inversesqrt: 'inverseSqrt',
  103. bitcast: 'bitcast<f32>',
  104. floatpack_snorm_2x16: 'pack2x16snorm',
  105. floatpack_unorm_2x16: 'pack2x16unorm',
  106. floatpack_float16_2x16: 'pack2x16float',
  107. floatunpack_snorm_2x16: 'unpack2x16snorm',
  108. floatunpack_unorm_2x16: 'unpack2x16unorm',
  109. floatunpack_float16_2x16: 'unpack2x16float'
  110. };
  111. //
  112. let diagnostics = '';
  113. if ( ( typeof navigator !== 'undefined' && /Firefox|Deno/g.test( navigator.userAgent ) ) !== true ) {
  114. diagnostics += 'diagnostic( off, derivative_uniformity );\n';
  115. }
  116. /**
  117. * A node builder targeting WGSL.
  118. *
  119. * This module generates WGSL shader code from node materials and also
  120. * generates the respective bindings and vertex buffer definitions. These
  121. * data are later used by the renderer to create render and compute pipelines
  122. * for render objects.
  123. *
  124. * @augments NodeBuilder
  125. */
  126. class WGSLNodeBuilder extends NodeBuilder {
  127. /**
  128. * Constructs a new WGSL node builder renderer.
  129. *
  130. * @param {Object3D} object - The 3D object.
  131. * @param {Renderer} renderer - The renderer.
  132. */
  133. constructor( object, renderer ) {
  134. super( object, renderer, new WGSLNodeParser() );
  135. /**
  136. * A dictionary that holds for each shader stage ('vertex', 'fragment', 'compute')
  137. * another dictionary which manages UBOs per group ('render','frame','object').
  138. *
  139. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  140. */
  141. this.uniformGroups = {};
  142. /**
  143. * A dictionary that holds for each shader stage a Map of builtins.
  144. *
  145. * @type {Object<string,Map<string,Object>>}
  146. */
  147. this.builtins = {};
  148. /**
  149. * A dictionary that holds for each shader stage a Set of directives.
  150. *
  151. * @type {Object<string,Set<string>>}
  152. */
  153. this.directives = {};
  154. /**
  155. * A map for managing scope arrays. Only relevant for when using
  156. * {@link WorkgroupInfoNode} in context of compute shaders.
  157. *
  158. * @type {Map<string,Object>}
  159. */
  160. this.scopedArrays = new Map();
  161. }
  162. /**
  163. * Generates the WGSL snippet for sampled textures.
  164. *
  165. * @private
  166. * @param {Texture} texture - The texture.
  167. * @param {string} textureProperty - The name of the texture uniform in the shader.
  168. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  169. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  170. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  171. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  172. * @return {string} The WGSL snippet.
  173. */
  174. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  175. if ( shaderStage === 'fragment' ) {
  176. if ( depthSnippet ) {
  177. if ( offsetSnippet ) {
  178. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ offsetSnippet } )`;
  179. }
  180. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  181. } else {
  182. if ( offsetSnippet ) {
  183. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ offsetSnippet } )`;
  184. }
  185. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  186. }
  187. } else {
  188. return this.generateTextureSampleLevel( texture, textureProperty, uvSnippet, '0', depthSnippet );
  189. }
  190. }
  191. /**
  192. * Generates the WGSL snippet when sampling textures with explicit mip level.
  193. *
  194. * @private
  195. * @param {Texture} texture - The texture.
  196. * @param {string} textureProperty - The name of the texture uniform in the shader.
  197. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  198. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  199. * @param {string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  200. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  201. * @return {string} The WGSL snippet.
  202. */
  203. generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  204. if ( this.isUnfilterable( texture ) === false ) {
  205. if ( offsetSnippet ) {
  206. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  207. }
  208. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  209. } else if ( this.isFilteredTexture( texture ) ) {
  210. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, offsetSnippet, levelSnippet );
  211. } else {
  212. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, levelSnippet );
  213. }
  214. }
  215. /**
  216. * Generates a wrap function used in context of textures.
  217. *
  218. * @param {Texture} texture - The texture to generate the function for.
  219. * @return {string} The name of the generated function.
  220. */
  221. generateWrapFunction( texture ) {
  222. const functionName = `tsl_coord_${ wrapNames[ texture.wrapS ] }S_${ wrapNames[ texture.wrapT ] }_${ texture.is3DTexture || texture.isData3DTexture ? '3d' : '2d' }T`;
  223. let nodeCode = wgslCodeCache[ functionName ];
  224. if ( nodeCode === undefined ) {
  225. const includes = [];
  226. // For 3D textures, use vec3f; for texture arrays, keep vec2f since array index is separate
  227. const coordType = texture.is3DTexture || texture.isData3DTexture ? 'vec3f' : 'vec2f';
  228. let code = `fn ${ functionName }( coord : ${ coordType } ) -> ${ coordType } {\n\n\treturn ${ coordType }(\n`;
  229. const addWrapSnippet = ( wrap, axis ) => {
  230. if ( wrap === RepeatWrapping ) {
  231. includes.push( wgslPolyfill.repeatWrapping_float );
  232. code += `\t\ttsl_repeatWrapping_float( coord.${ axis } )`;
  233. } else if ( wrap === ClampToEdgeWrapping ) {
  234. includes.push( wgslPolyfill.clampWrapping_float );
  235. code += `\t\ttsl_clampWrapping_float( coord.${ axis } )`;
  236. } else if ( wrap === MirroredRepeatWrapping ) {
  237. includes.push( wgslPolyfill.mirrorWrapping_float );
  238. code += `\t\ttsl_mirrorWrapping_float( coord.${ axis } )`;
  239. } else {
  240. code += `\t\tcoord.${ axis }`;
  241. warn( `WebGPURenderer: Unsupported texture wrap type "${ wrap }" for vertex shader.` );
  242. }
  243. };
  244. addWrapSnippet( texture.wrapS, 'x' );
  245. code += ',\n';
  246. addWrapSnippet( texture.wrapT, 'y' );
  247. if ( texture.is3DTexture || texture.isData3DTexture ) {
  248. code += ',\n';
  249. addWrapSnippet( texture.wrapR, 'z' );
  250. }
  251. code += '\n\t);\n\n}\n';
  252. wgslCodeCache[ functionName ] = nodeCode = new CodeNode( code, includes );
  253. }
  254. nodeCode.build( this );
  255. return functionName;
  256. }
  257. /**
  258. * Generates the array declaration string.
  259. *
  260. * @param {string} type - The type.
  261. * @param {?number} [count] - The count.
  262. * @return {string} The generated value as a shader string.
  263. */
  264. generateArrayDeclaration( type, count ) {
  265. return `array< ${ this.getType( type ) }, ${ count } >`;
  266. }
  267. /**
  268. * Generates a WGSL variable that holds the texture dimension of the given texture.
  269. * It also returns information about the number of layers (elements) of an arrayed
  270. * texture as well as the cube face count of cube textures.
  271. *
  272. * @param {Texture} texture - The texture to generate the function for.
  273. * @param {string} textureProperty - The name of the video texture uniform in the shader.
  274. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  275. * @return {string} The name of the dimension variable.
  276. */
  277. generateTextureDimension( texture, textureProperty, levelSnippet ) {
  278. const textureData = this.getDataFromNode( texture, this.shaderStage, this.globalCache );
  279. if ( textureData.dimensionsSnippet === undefined ) textureData.dimensionsSnippet = {};
  280. let textureDimensionNode = textureData.dimensionsSnippet[ levelSnippet ];
  281. if ( textureData.dimensionsSnippet[ levelSnippet ] === undefined ) {
  282. let textureDimensionsParams;
  283. let dimensionType;
  284. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  285. const isMultisampled = primarySamples > 1;
  286. if ( texture.is3DTexture || texture.isData3DTexture ) {
  287. dimensionType = 'vec3<u32>';
  288. } else {
  289. // Regular 2D textures, depth textures, etc.
  290. dimensionType = 'vec2<u32>';
  291. }
  292. // Build parameters string based on texture type and multisampling
  293. if ( isMultisampled || texture.isStorageTexture ) {
  294. textureDimensionsParams = textureProperty;
  295. } else {
  296. textureDimensionsParams = `${textureProperty}${levelSnippet ? `, u32( ${ levelSnippet } )` : ''}`;
  297. }
  298. textureDimensionNode = new VarNode( new ExpressionNode( `textureDimensions( ${ textureDimensionsParams } )`, dimensionType ) );
  299. textureData.dimensionsSnippet[ levelSnippet ] = textureDimensionNode;
  300. if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.is3DTexture || texture.isData3DTexture ) {
  301. textureData.arrayLayerCount = new VarNode(
  302. new ExpressionNode(
  303. `textureNumLayers(${textureProperty})`,
  304. 'u32'
  305. )
  306. );
  307. }
  308. // For cube textures, we know it's always 6 faces
  309. if ( texture.isTextureCube ) {
  310. textureData.cubeFaceCount = new VarNode(
  311. new ExpressionNode( '6u', 'u32' )
  312. );
  313. }
  314. }
  315. return textureDimensionNode.build( this );
  316. }
  317. /**
  318. * Generates the WGSL snippet for a manual filtered texture.
  319. *
  320. * @param {Texture} texture - The texture.
  321. * @param {string} textureProperty - The name of the texture uniform in the shader.
  322. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  323. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  324. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  325. * @return {string} The WGSL snippet.
  326. */
  327. generateFilteredTexture( texture, textureProperty, uvSnippet, offsetSnippet, levelSnippet = '0u' ) {
  328. this._include( 'biquadraticTexture' );
  329. const wrapFunction = this.generateWrapFunction( texture );
  330. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  331. if ( offsetSnippet ) {
  332. uvSnippet = `${ uvSnippet } + vec2<f32>(${ offsetSnippet }) / ${ textureDimension }`;
  333. }
  334. return `tsl_biquadraticTexture( ${ textureProperty }, ${ wrapFunction }( ${ uvSnippet } ), ${ textureDimension }, u32( ${ levelSnippet } ) )`;
  335. }
  336. /**
  337. * Generates the WGSL snippet for a texture lookup with explicit level-of-detail.
  338. * Since it's a lookup, no sampling or filtering is applied.
  339. *
  340. * @param {Texture} texture - The texture.
  341. * @param {string} textureProperty - The name of the texture uniform in the shader.
  342. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  343. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  344. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  345. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  346. * @return {string} The WGSL snippet.
  347. */
  348. generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, levelSnippet = '0u' ) {
  349. const wrapFunction = this.generateWrapFunction( texture );
  350. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  351. const vecType = texture.is3DTexture || texture.isData3DTexture ? 'vec3' : 'vec2';
  352. if ( offsetSnippet ) {
  353. uvSnippet = `${ uvSnippet } + ${ vecType }<f32>(${ offsetSnippet }) / ${ vecType }<f32>( ${ textureDimension } )`;
  354. }
  355. const coordSnippet = `${ vecType }<u32>( ${ wrapFunction }( ${ uvSnippet } ) * ${ vecType }<f32>( ${ textureDimension } ) )`;
  356. return this.generateTextureLoad( texture, textureProperty, coordSnippet, levelSnippet, depthSnippet, null );
  357. }
  358. /**
  359. * Generates the WGSL snippet that reads a single texel from a texture without sampling or filtering.
  360. *
  361. * @param {Texture} texture - The texture.
  362. * @param {string} textureProperty - The name of the texture uniform in the shader.
  363. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  364. * @param {?string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  365. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  366. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  367. * @return {string} The WGSL snippet.
  368. */
  369. generateTextureLoad( texture, textureProperty, uvIndexSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  370. if ( levelSnippet === null ) levelSnippet = '0u';
  371. if ( offsetSnippet ) {
  372. uvIndexSnippet = `${ uvIndexSnippet } + ${ offsetSnippet }`;
  373. }
  374. let snippet;
  375. if ( depthSnippet ) {
  376. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, u32( ${ levelSnippet } ) )`;
  377. } else {
  378. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, u32( ${ levelSnippet } ) )`;
  379. if ( this.renderer.backend.compatibilityMode && texture.isDepthTexture ) {
  380. snippet += '.x';
  381. }
  382. }
  383. return snippet;
  384. }
  385. /**
  386. * Generates the WGSL snippet that writes a single texel to a texture.
  387. *
  388. * @param {Texture} texture - The texture.
  389. * @param {string} textureProperty - The name of the texture uniform in the shader.
  390. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  391. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  392. * @param {string} valueSnippet - A WGSL snippet that represent the new texel value.
  393. * @return {string} The WGSL snippet.
  394. */
  395. generateTextureStore( texture, textureProperty, uvIndexSnippet, depthSnippet, valueSnippet ) {
  396. let snippet;
  397. if ( depthSnippet ) {
  398. snippet = `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, ${ valueSnippet } )`;
  399. } else {
  400. snippet = `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  401. }
  402. return snippet;
  403. }
  404. /**
  405. * Returns `true` if the sampled values of the given texture should be compared against a reference value.
  406. *
  407. * @param {Texture} texture - The texture.
  408. * @return {boolean} Whether the sampled values of the given texture should be compared against a reference value or not.
  409. */
  410. isSampleCompare( texture ) {
  411. return texture.isDepthTexture === true && texture.compareFunction !== null;
  412. }
  413. /**
  414. * Returns `true` if the given texture is unfilterable.
  415. *
  416. * @param {Texture} texture - The texture.
  417. * @return {boolean} Whether the given texture is unfilterable or not.
  418. */
  419. isUnfilterable( texture ) {
  420. return this.getComponentTypeFromTexture( texture ) !== 'float' ||
  421. ( ! this.isAvailable( 'float32Filterable' ) && texture.isDataTexture === true && texture.type === FloatType ) ||
  422. ( this.isSampleCompare( texture ) === false && texture.minFilter === NearestFilter && texture.magFilter === NearestFilter ) ||
  423. this.renderer.backend.utils.getTextureSampleData( texture ).primarySamples > 1;
  424. }
  425. /**
  426. * Generates the WGSL snippet for sampling/loading the given texture.
  427. *
  428. * @param {Texture} texture - The texture.
  429. * @param {string} textureProperty - The name of the texture uniform in the shader.
  430. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  431. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  432. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  433. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  434. * @return {string} The WGSL snippet.
  435. */
  436. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  437. let snippet = null;
  438. if ( this.isUnfilterable( texture ) ) {
  439. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, '0', shaderStage );
  440. } else {
  441. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, shaderStage );
  442. }
  443. return snippet;
  444. }
  445. /**
  446. * Generates the WGSL snippet for sampling/loading the given texture using explicit gradients.
  447. *
  448. * @param {Texture} texture - The texture.
  449. * @param {string} textureProperty - The name of the texture uniform in the shader.
  450. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  451. * @param {Array<string>} gradSnippet - An array holding both gradient WGSL snippets.
  452. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  453. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  454. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  455. * @return {string} The WGSL snippet.
  456. */
  457. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  458. if ( shaderStage === 'fragment' ) {
  459. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  460. if ( offsetSnippet ) {
  461. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] }, ${ offsetSnippet } )`;
  462. }
  463. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  464. } else {
  465. error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  466. }
  467. }
  468. /**
  469. * Generates the WGSL snippet for sampling a depth texture and comparing the sampled depth values
  470. * against a reference value.
  471. *
  472. * @param {Texture} texture - The texture.
  473. * @param {string} textureProperty - The name of the texture uniform in the shader.
  474. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  475. * @param {string} compareSnippet - A WGSL snippet that represents the reference value.
  476. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  477. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  478. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  479. * @return {string} The WGSL snippet.
  480. */
  481. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  482. if ( shaderStage === 'fragment' ) {
  483. if ( texture.isDepthTexture === true && texture.isArrayTexture === true ) {
  484. if ( offsetSnippet ) {
  485. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet }, ${ offsetSnippet } )`;
  486. }
  487. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } )`;
  488. }
  489. if ( offsetSnippet ) {
  490. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet }, ${ offsetSnippet } )`;
  491. }
  492. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  493. } else {
  494. error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  495. }
  496. }
  497. /**
  498. * Generates the WGSL snippet when sampling textures with explicit mip level.
  499. *
  500. * @param {Texture} texture - The texture.
  501. * @param {string} textureProperty - The name of the texture uniform in the shader.
  502. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  503. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  504. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  505. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  506. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  507. * @return {string} The WGSL snippet.
  508. */
  509. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  510. if ( this.isUnfilterable( texture ) === false ) {
  511. if ( offsetSnippet ) {
  512. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  513. }
  514. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  515. } else if ( this.isFilteredTexture( texture ) ) {
  516. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, offsetSnippet, levelSnippet );
  517. } else {
  518. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, levelSnippet );
  519. }
  520. }
  521. /**
  522. * Generates the WGSL snippet when sampling textures with a bias to the mip level.
  523. *
  524. * @param {Texture} texture - The texture.
  525. * @param {string} textureProperty - The name of the texture uniform in the shader.
  526. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  527. * @param {string} biasSnippet - A WGSL snippet that represents the bias to apply to the mip level before sampling.
  528. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  529. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  530. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  531. * @return {string} The WGSL snippet.
  532. */
  533. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  534. if ( shaderStage === 'fragment' ) {
  535. if ( offsetSnippet ) {
  536. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet }, ${ offsetSnippet } )`;
  537. }
  538. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  539. } else {
  540. error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  541. }
  542. }
  543. /**
  544. * Returns a WGSL snippet that represents the property name of the given node.
  545. *
  546. * @param {Node} node - The node.
  547. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  548. * @return {string} The property name.
  549. */
  550. getPropertyName( node, shaderStage = this.shaderStage ) {
  551. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  552. if ( shaderStage === 'vertex' ) {
  553. return `varyings.${ node.name }`;
  554. }
  555. } else if ( node.isNodeUniform === true ) {
  556. const name = node.name;
  557. const type = node.type;
  558. if ( type === 'texture' || type === 'cubeTexture' || type === 'cubeDepthTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  559. return name;
  560. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  561. if ( this.isCustomStruct( node ) ) {
  562. return name;
  563. }
  564. return name + '.value';
  565. } else {
  566. return node.groupNode.name + '.' + name;
  567. }
  568. }
  569. return super.getPropertyName( node );
  570. }
  571. /**
  572. * Returns the output struct name.
  573. *
  574. * @return {string} The name of the output struct.
  575. */
  576. getOutputStructName() {
  577. return 'output';
  578. }
  579. /**
  580. * Returns the native shader operator name for a given generic name.
  581. *
  582. * @param {string} op - The operator name to resolve.
  583. * @return {?string} The resolved operator name.
  584. */
  585. getFunctionOperator( op ) {
  586. const fnOp = wgslFnOpLib[ op ];
  587. if ( fnOp !== undefined ) {
  588. this._include( fnOp );
  589. return fnOp;
  590. }
  591. return null;
  592. }
  593. /**
  594. * Returns the node access for the given node and shader stage.
  595. *
  596. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  597. * @param {string} shaderStage - The shader stage.
  598. * @return {string} The node access.
  599. */
  600. getNodeAccess( node, shaderStage ) {
  601. if ( shaderStage !== 'compute' ) {
  602. if ( node.isAtomic === true ) {
  603. warn( 'WebGPURenderer: Atomic operations are only supported in compute shaders.' );
  604. return NodeAccess.READ_WRITE;
  605. }
  606. return NodeAccess.READ_ONLY;
  607. }
  608. return node.access;
  609. }
  610. /**
  611. * Returns A WGSL snippet representing the storage access.
  612. *
  613. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  614. * @param {string} shaderStage - The shader stage.
  615. * @return {string} The WGSL snippet representing the storage access.
  616. */
  617. getStorageAccess( node, shaderStage ) {
  618. return accessNames[ this.getNodeAccess( node, shaderStage ) ];
  619. }
  620. /**
  621. * This method is one of the more important ones since it's responsible
  622. * for generating a matching binding instance for the given uniform node.
  623. *
  624. * These bindings are later used in the renderer to create bind groups
  625. * and layouts.
  626. *
  627. * @param {UniformNode} node - The uniform node.
  628. * @param {string} type - The node data type.
  629. * @param {string} shaderStage - The shader stage.
  630. * @param {?string} [name=null] - An optional uniform name.
  631. * @return {NodeUniform} The node uniform object.
  632. */
  633. getUniformFromNode( node, type, shaderStage, name = null ) {
  634. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  635. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  636. if ( nodeData.uniformGPU === undefined ) {
  637. let uniformGPU;
  638. const group = node.groupNode;
  639. const groupName = group.name;
  640. const bindings = this.getBindGroupArray( groupName, shaderStage );
  641. if ( type === 'texture' || type === 'cubeTexture' || type === 'cubeDepthTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  642. let texture = null;
  643. const access = this.getNodeAccess( node, shaderStage );
  644. if ( type === 'texture' || type === 'storageTexture' ) {
  645. if ( node.value.is3DTexture === true ) {
  646. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  647. } else {
  648. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, access );
  649. }
  650. } else if ( type === 'cubeTexture' || type === 'cubeDepthTexture' ) {
  651. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, access );
  652. } else if ( type === 'texture3D' ) {
  653. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  654. }
  655. texture.store = node.isStorageTextureNode === true;
  656. texture.mipLevel = texture.store ? node.mipLevel : 0;
  657. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  658. if ( this.isUnfilterable( node.value ) === false && texture.store === false ) {
  659. const sampler = new NodeSampler( `${ uniformNode.name }_sampler`, uniformNode.node, group );
  660. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  661. bindings.push( sampler, texture );
  662. uniformGPU = [ sampler, texture ];
  663. } else {
  664. bindings.push( texture );
  665. uniformGPU = [ texture ];
  666. }
  667. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  668. const sharedData = this.getSharedDataFromNode( node );
  669. let buffer = sharedData.buffer;
  670. if ( buffer === undefined ) {
  671. const bufferClass = type === 'buffer' ? NodeUniformBuffer : NodeStorageBuffer;
  672. buffer = new bufferClass( node, group );
  673. sharedData.buffer = buffer;
  674. }
  675. buffer.setVisibility( buffer.getVisibility() | gpuShaderStageLib[ shaderStage ] );
  676. bindings.push( buffer );
  677. uniformGPU = buffer;
  678. uniformNode.name = name ? name : 'NodeBuffer_' + uniformNode.id;
  679. } else {
  680. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  681. let uniformsGroup = uniformsStage[ groupName ];
  682. if ( uniformsGroup === undefined ) {
  683. uniformsGroup = new NodeUniformsGroup( groupName, group );
  684. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  685. uniformsStage[ groupName ] = uniformsGroup;
  686. bindings.push( uniformsGroup );
  687. }
  688. uniformGPU = this.getNodeUniform( uniformNode, type );
  689. uniformsGroup.addUniform( uniformGPU );
  690. }
  691. nodeData.uniformGPU = uniformGPU;
  692. }
  693. return uniformNode;
  694. }
  695. /**
  696. * This method should be used whenever builtins are required in nodes.
  697. * The internal builtins data structure will make sure builtins are
  698. * defined in the WGSL source.
  699. *
  700. * @param {string} name - The builtin name.
  701. * @param {string} property - The property name.
  702. * @param {string} type - The node data type.
  703. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  704. * @return {string} The property name.
  705. */
  706. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  707. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  708. if ( map.has( name ) === false ) {
  709. map.set( name, {
  710. name,
  711. property,
  712. type
  713. } );
  714. }
  715. return property;
  716. }
  717. /**
  718. * Returns `true` if the given builtin is defined in the given shader stage.
  719. *
  720. * @param {string} name - The builtin name.
  721. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  722. * @return {boolean} Whether the given builtin is defined in the given shader stage or not.
  723. */
  724. hasBuiltin( name, shaderStage = this.shaderStage ) {
  725. return ( this.builtins[ shaderStage ] !== undefined && this.builtins[ shaderStage ].has( name ) );
  726. }
  727. /**
  728. * Returns the vertex index builtin.
  729. *
  730. * @return {string} The vertex index.
  731. */
  732. getVertexIndex() {
  733. if ( this.shaderStage === 'vertex' ) {
  734. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  735. }
  736. return 'vertexIndex';
  737. }
  738. /**
  739. * Builds the given shader node.
  740. *
  741. * @param {ShaderNodeInternal} shaderNode - The shader node.
  742. * @return {string} The WGSL function code.
  743. */
  744. buildFunctionCode( shaderNode ) {
  745. const layout = shaderNode.layout;
  746. const flowData = this.flowShaderNode( shaderNode );
  747. const parameters = [];
  748. for ( const input of layout.inputs ) {
  749. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  750. }
  751. //
  752. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  753. ${ flowData.vars }
  754. ${ flowData.code }
  755. `;
  756. if ( flowData.result ) {
  757. code += `\treturn ${ flowData.result };\n`;
  758. }
  759. code += '\n}\n';
  760. //
  761. return code;
  762. }
  763. /**
  764. * Contextually returns either the vertex stage instance index builtin
  765. * or the linearized index of an compute invocation within a grid of workgroups.
  766. *
  767. * @return {string} The instance index.
  768. */
  769. getInstanceIndex() {
  770. if ( this.shaderStage === 'vertex' ) {
  771. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  772. }
  773. return 'instanceIndex';
  774. }
  775. /**
  776. * Returns a builtin representing the index of a compute invocation within the scope of a workgroup load.
  777. *
  778. * @return {string} The invocation local index.
  779. */
  780. getInvocationLocalIndex() {
  781. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  782. }
  783. /**
  784. * Returns a builtin representing the size of a subgroup within the current shader.
  785. *
  786. * @return {string} The subgroup size.
  787. */
  788. getSubgroupSize() {
  789. this.enableSubGroups();
  790. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  791. }
  792. /**
  793. * Returns a builtin representing the index of a compute invocation within the scope of a subgroup.
  794. *
  795. * @return {string} The invocation subgroup index.
  796. */
  797. getInvocationSubgroupIndex() {
  798. this.enableSubGroups();
  799. return this.getBuiltin( 'subgroup_invocation_id', 'invocationSubgroupIndex', 'u32', 'attribute' );
  800. }
  801. /**
  802. * Returns a builtin representing the index of a compute invocation's subgroup within its workgroup.
  803. *
  804. * @return {string} The subgroup index.
  805. */
  806. getSubgroupIndex() {
  807. this.enableSubGroups();
  808. return this.getBuiltin( 'subgroup_id', 'subgroupIndex', 'u32', 'attribute' );
  809. }
  810. /**
  811. * Overwritten as a NOP since this method is intended for the WebGL 2 backend.
  812. *
  813. * @return {null} Null.
  814. */
  815. getDrawIndex() {
  816. return null;
  817. }
  818. /**
  819. * Returns the front facing builtin.
  820. *
  821. * @return {string} The front facing builtin.
  822. */
  823. getFrontFacing() {
  824. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  825. }
  826. /**
  827. * Returns the frag coord builtin.
  828. *
  829. * @return {string} The frag coord builtin.
  830. */
  831. getFragCoord() {
  832. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  833. }
  834. /**
  835. * Returns the frag depth builtin.
  836. *
  837. * @return {string} The frag depth builtin.
  838. */
  839. getFragDepth() {
  840. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  841. }
  842. /**
  843. * Returns the clip distances builtin.
  844. *
  845. * @return {string} The clip distances builtin.
  846. */
  847. getClipDistance() {
  848. return 'varyings.hw_clip_distances';
  849. }
  850. /**
  851. * Whether to flip texture data along its vertical axis or not.
  852. *
  853. * @return {boolean} Returns always `false` in context of WGSL.
  854. */
  855. isFlipY() {
  856. return false;
  857. }
  858. /**
  859. * Enables the given directive for the given shader stage.
  860. *
  861. * @param {string} name - The directive name.
  862. * @param {string} [shaderStage=this.shaderStage] - The shader stage to enable the directive for.
  863. */
  864. enableDirective( name, shaderStage = this.shaderStage ) {
  865. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  866. stage.add( name );
  867. }
  868. /**
  869. * Returns the directives of the given shader stage as a WGSL string.
  870. *
  871. * @param {string} shaderStage - The shader stage.
  872. * @return {string} A WGSL snippet that enables the directives of the given stage.
  873. */
  874. getDirectives( shaderStage ) {
  875. const snippets = [];
  876. const directives = this.directives[ shaderStage ];
  877. if ( directives !== undefined ) {
  878. for ( const directive of directives ) {
  879. snippets.push( `enable ${directive};` );
  880. }
  881. }
  882. return snippets.join( '\n' );
  883. }
  884. /**
  885. * Enables the 'subgroups' directive.
  886. */
  887. enableSubGroups() {
  888. this.enableDirective( 'subgroups' );
  889. }
  890. /**
  891. * Enables the 'subgroups-f16' directive.
  892. */
  893. enableSubgroupsF16() {
  894. this.enableDirective( 'subgroups-f16' );
  895. }
  896. /**
  897. * Enables the 'clip_distances' directive.
  898. */
  899. enableClipDistances() {
  900. this.enableDirective( 'clip_distances' );
  901. }
  902. /**
  903. * Enables the 'f16' directive.
  904. */
  905. enableShaderF16() {
  906. this.enableDirective( 'f16' );
  907. }
  908. /**
  909. * Enables the 'dual_source_blending' directive.
  910. */
  911. enableDualSourceBlending() {
  912. this.enableDirective( 'dual_source_blending' );
  913. }
  914. /**
  915. * Enables hardware clipping.
  916. *
  917. * @param {string} planeCount - The clipping plane count.
  918. */
  919. enableHardwareClipping( planeCount ) {
  920. this.enableClipDistances();
  921. this.getBuiltin( 'clip_distances', 'hw_clip_distances', `array<f32, ${ planeCount } >`, 'vertex' );
  922. }
  923. /**
  924. * Returns the builtins of the given shader stage as a WGSL string.
  925. *
  926. * @param {string} shaderStage - The shader stage.
  927. * @return {string} A WGSL snippet that represents the builtins of the given stage.
  928. */
  929. getBuiltins( shaderStage ) {
  930. const snippets = [];
  931. const builtins = this.builtins[ shaderStage ];
  932. if ( builtins !== undefined ) {
  933. for ( const { name, property, type } of builtins.values() ) {
  934. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  935. }
  936. }
  937. return snippets.join( ',\n\t' );
  938. }
  939. /**
  940. * This method should be used when a new scoped buffer is used in context of
  941. * compute shaders. It adds the array to the internal data structure which is
  942. * later used to generate the respective WGSL.
  943. *
  944. * @param {string} name - The array name.
  945. * @param {string} scope - The scope.
  946. * @param {string} bufferType - The buffer type.
  947. * @param {string} bufferCount - The buffer count.
  948. * @return {string} The array name.
  949. */
  950. getScopedArray( name, scope, bufferType, bufferCount ) {
  951. if ( this.scopedArrays.has( name ) === false ) {
  952. this.scopedArrays.set( name, {
  953. name,
  954. scope,
  955. bufferType,
  956. bufferCount
  957. } );
  958. }
  959. return name;
  960. }
  961. /**
  962. * Returns the scoped arrays of the given shader stage as a WGSL string.
  963. *
  964. * @param {string} shaderStage - The shader stage.
  965. * @return {string|undefined} The WGSL snippet that defines the scoped arrays.
  966. * Returns `undefined` when used in the vertex or fragment stage.
  967. */
  968. getScopedArrays( shaderStage ) {
  969. if ( shaderStage !== 'compute' ) {
  970. return;
  971. }
  972. const snippets = [];
  973. for ( const { name, scope, bufferType, bufferCount } of this.scopedArrays.values() ) {
  974. const type = this.getType( bufferType );
  975. snippets.push( `var<${scope}> ${name}: array< ${type}, ${bufferCount} >;` );
  976. }
  977. return snippets.join( '\n' );
  978. }
  979. /**
  980. * Returns the shader attributes of the given shader stage as a WGSL string.
  981. *
  982. * @param {string} shaderStage - The shader stage.
  983. * @return {string} The WGSL snippet that defines the shader attributes.
  984. */
  985. getAttributes( shaderStage ) {
  986. const snippets = [];
  987. if ( shaderStage === 'compute' ) {
  988. this.getBuiltin( 'global_invocation_id', 'globalId', 'vec3<u32>', 'attribute' );
  989. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  990. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  991. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  992. if ( this.renderer.hasFeature( 'subgroups' ) ) {
  993. this.enableDirective( 'subgroups', shaderStage );
  994. this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  995. }
  996. }
  997. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  998. const builtins = this.getBuiltins( 'attribute' );
  999. if ( builtins ) snippets.push( builtins );
  1000. const attributes = this.getAttributesArray();
  1001. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  1002. const attribute = attributes[ index ];
  1003. const name = attribute.name;
  1004. const type = this.getType( attribute.type );
  1005. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  1006. }
  1007. }
  1008. return snippets.join( ',\n\t' );
  1009. }
  1010. /**
  1011. * Returns the members of the given struct type node as a WGSL string.
  1012. *
  1013. * @param {StructTypeNode} struct - The struct type node.
  1014. * @return {string} The WGSL snippet that defines the struct members.
  1015. */
  1016. getStructMembers( struct ) {
  1017. const snippets = [];
  1018. for ( const member of struct.members ) {
  1019. const prefix = struct.output ? '@location( ' + member.index + ' ) ' : '';
  1020. let type = this.getType( member.type );
  1021. if ( member.atomic ) {
  1022. type = 'atomic< ' + type + ' >';
  1023. }
  1024. snippets.push( `\t${ prefix + member.name } : ${ type }` );
  1025. }
  1026. if ( struct.output ) {
  1027. snippets.push( `\t${ this.getBuiltins( 'output' ) }` );
  1028. }
  1029. return snippets.join( ',\n' );
  1030. }
  1031. /**
  1032. * Returns the structs of the given shader stage as a WGSL string.
  1033. *
  1034. * @param {string} shaderStage - The shader stage.
  1035. * @return {string} The WGSL snippet that defines the structs.
  1036. */
  1037. getStructs( shaderStage ) {
  1038. let result = '';
  1039. const structs = this.structs[ shaderStage ];
  1040. if ( structs.length > 0 ) {
  1041. const snippets = [];
  1042. for ( const struct of structs ) {
  1043. let snippet = `struct ${ struct.name } {\n`;
  1044. snippet += this.getStructMembers( struct );
  1045. snippet += '\n};';
  1046. snippets.push( snippet );
  1047. }
  1048. result = '\n' + snippets.join( '\n\n' ) + '\n';
  1049. }
  1050. return result;
  1051. }
  1052. /**
  1053. * Returns a WGSL string representing a variable.
  1054. *
  1055. * @param {string} type - The variable's type.
  1056. * @param {string} name - The variable's name.
  1057. * @param {?number} [count=null] - The array length.
  1058. * @return {string} The WGSL snippet that defines a variable.
  1059. */
  1060. getVar( type, name, count = null ) {
  1061. let snippet = `var ${ name } : `;
  1062. if ( count !== null ) {
  1063. snippet += this.generateArrayDeclaration( type, count );
  1064. } else {
  1065. snippet += this.getType( type );
  1066. }
  1067. return snippet;
  1068. }
  1069. /**
  1070. * Returns the variables of the given shader stage as a WGSL string.
  1071. *
  1072. * @param {string} shaderStage - The shader stage.
  1073. * @return {string} The WGSL snippet that defines the variables.
  1074. */
  1075. getVars( shaderStage ) {
  1076. const snippets = [];
  1077. const vars = this.vars[ shaderStage ];
  1078. if ( vars !== undefined ) {
  1079. for ( const variable of vars ) {
  1080. snippets.push( `\t${ this.getVar( variable.type, variable.name, variable.count ) };` );
  1081. }
  1082. }
  1083. return `\n${ snippets.join( '\n' ) }\n`;
  1084. }
  1085. /**
  1086. * Returns the varyings of the given shader stage as a WGSL string.
  1087. *
  1088. * @param {string} shaderStage - The shader stage.
  1089. * @return {string} The WGSL snippet that defines the varyings.
  1090. */
  1091. getVaryings( shaderStage ) {
  1092. const snippets = [];
  1093. if ( shaderStage === 'vertex' ) {
  1094. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  1095. }
  1096. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  1097. const varyings = this.varyings;
  1098. const vars = this.vars[ shaderStage ];
  1099. for ( let index = 0; index < varyings.length; index ++ ) {
  1100. const varying = varyings[ index ];
  1101. if ( varying.needsInterpolation ) {
  1102. let attributesSnippet = `@location( ${index} )`;
  1103. if ( varying.interpolationType ) {
  1104. const samplingSnippet = varying.interpolationSampling !== null ? `, ${ varying.interpolationSampling } )` : ' )';
  1105. attributesSnippet += ` @interpolate( ${ varying.interpolationType }${ samplingSnippet }`;
  1106. // Otherwise, optimize interpolation when sensible
  1107. } else if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  1108. attributesSnippet += ` @interpolate( ${ this.renderer.backend.compatibilityMode ? 'flat, either' : 'flat' } )`;
  1109. }
  1110. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  1111. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  1112. vars.push( varying );
  1113. }
  1114. }
  1115. }
  1116. const builtins = this.getBuiltins( shaderStage );
  1117. if ( builtins ) snippets.push( builtins );
  1118. const code = snippets.join( ',\n\t' );
  1119. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  1120. }
  1121. isCustomStruct( nodeUniform ) {
  1122. const attribute = nodeUniform.value;
  1123. const bufferNode = nodeUniform.node;
  1124. const isAttributeStructType = ( attribute.isBufferAttribute || attribute.isInstancedBufferAttribute ) && bufferNode.structTypeNode !== null;
  1125. const isStructArray =
  1126. ( bufferNode.value && bufferNode.value.array ) &&
  1127. ( typeof bufferNode.value.itemSize === 'number' && bufferNode.value.array.length > bufferNode.value.itemSize );
  1128. return isAttributeStructType && ! isStructArray;
  1129. }
  1130. /**
  1131. * Returns the uniforms of the given shader stage as a WGSL string.
  1132. *
  1133. * @param {string} shaderStage - The shader stage.
  1134. * @return {string} The WGSL snippet that defines the uniforms.
  1135. */
  1136. getUniforms( shaderStage ) {
  1137. const uniforms = this.uniforms[ shaderStage ];
  1138. const bindingSnippets = [];
  1139. const bufferSnippets = [];
  1140. const structSnippets = [];
  1141. const uniformGroups = {};
  1142. for ( const uniform of uniforms ) {
  1143. const groupName = uniform.groupNode.name;
  1144. const uniformIndexes = this.bindingsIndexes[ groupName ];
  1145. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'cubeDepthTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  1146. const texture = uniform.node.value;
  1147. if ( this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  1148. if ( this.isSampleCompare( texture ) ) {
  1149. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  1150. } else {
  1151. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  1152. }
  1153. }
  1154. let textureType;
  1155. let multisampled = '';
  1156. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  1157. if ( primarySamples > 1 ) {
  1158. multisampled = '_multisampled';
  1159. }
  1160. if ( texture.isCubeTexture === true && texture.isDepthTexture === true ) {
  1161. textureType = 'texture_depth_cube';
  1162. } else if ( texture.isCubeTexture === true ) {
  1163. textureType = 'texture_cube<f32>';
  1164. } else if ( texture.isDepthTexture === true ) {
  1165. if ( this.renderer.backend.compatibilityMode && texture.compareFunction === null ) {
  1166. textureType = `texture${ multisampled }_2d<f32>`;
  1167. } else {
  1168. textureType = `texture_depth${ multisampled }_2d${ texture.isArrayTexture === true ? '_array' : '' }`;
  1169. }
  1170. } else if ( uniform.node.isStorageTextureNode === true ) {
  1171. const format = getFormat( texture );
  1172. const access = this.getStorageAccess( uniform.node, shaderStage );
  1173. const is3D = uniform.node.value.is3DTexture;
  1174. const isArrayTexture = uniform.node.value.isArrayTexture;
  1175. const dimension = is3D ? '3d' : `2d${ isArrayTexture ? '_array' : '' }`;
  1176. textureType = `texture_storage_${ dimension }<${ format }, ${ access }>`;
  1177. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  1178. textureType = 'texture_2d_array<f32>';
  1179. } else if ( texture.is3DTexture === true || texture.isData3DTexture === true ) {
  1180. textureType = 'texture_3d<f32>';
  1181. } else {
  1182. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  1183. textureType = `texture${ multisampled }_2d<${ componentPrefix }32>`;
  1184. }
  1185. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  1186. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' || uniform.type === 'indirectStorageBuffer' ) {
  1187. const bufferNode = uniform.node;
  1188. const bufferType = this.getType( bufferNode.getNodeType( this ) );
  1189. const bufferCount = bufferNode.bufferCount;
  1190. const bufferCountSnippet = bufferCount > 0 && uniform.type === 'buffer' ? ', ' + bufferCount : '';
  1191. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode, shaderStage ) }` : 'uniform';
  1192. if ( this.isCustomStruct( uniform ) ) {
  1193. bufferSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var<${ bufferAccessMode }> ${ uniform.name } : ${ bufferType };` );
  1194. } else {
  1195. const bufferTypeSnippet = bufferNode.isAtomic ? `atomic<${ bufferType }>` : `${ bufferType }`;
  1196. const bufferSnippet = `\tvalue : array< ${ bufferTypeSnippet }${ bufferCountSnippet } >`;
  1197. bufferSnippets.push( this._getWGSLStructBinding( uniform.name, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  1198. }
  1199. } else {
  1200. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  1201. const groupName = uniform.groupNode.name;
  1202. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  1203. index: uniformIndexes.binding ++,
  1204. id: uniformIndexes.group,
  1205. snippets: []
  1206. } );
  1207. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  1208. }
  1209. }
  1210. for ( const name in uniformGroups ) {
  1211. const group = uniformGroups[ name ];
  1212. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  1213. }
  1214. let code = bindingSnippets.join( '\n' );
  1215. code += bufferSnippets.join( '\n' );
  1216. code += structSnippets.join( '\n' );
  1217. return code;
  1218. }
  1219. /**
  1220. * Controls the code build of the shader stages.
  1221. */
  1222. buildCode() {
  1223. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  1224. this.sortBindingGroups();
  1225. for ( const shaderStage in shadersData ) {
  1226. this.shaderStage = shaderStage;
  1227. const stageData = shadersData[ shaderStage ];
  1228. stageData.uniforms = this.getUniforms( shaderStage );
  1229. stageData.attributes = this.getAttributes( shaderStage );
  1230. stageData.varyings = this.getVaryings( shaderStage );
  1231. stageData.structs = this.getStructs( shaderStage );
  1232. stageData.vars = this.getVars( shaderStage );
  1233. stageData.codes = this.getCodes( shaderStage );
  1234. stageData.directives = this.getDirectives( shaderStage );
  1235. stageData.scopedArrays = this.getScopedArrays( shaderStage );
  1236. //
  1237. let flow = '// code\n\n';
  1238. flow += this.flowCode[ shaderStage ];
  1239. const flowNodes = this.flowNodes[ shaderStage ];
  1240. const mainNode = flowNodes[ flowNodes.length - 1 ];
  1241. const outputNode = mainNode.outputNode;
  1242. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  1243. for ( const node of flowNodes ) {
  1244. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  1245. const slotName = node.name;
  1246. if ( slotName ) {
  1247. if ( flow.length > 0 ) flow += '\n';
  1248. flow += `\t// flow -> ${ slotName }\n`;
  1249. }
  1250. flow += `${ flowSlotData.code }\n\t`;
  1251. if ( node === mainNode && shaderStage !== 'compute' ) {
  1252. flow += '// result\n\n\t';
  1253. if ( shaderStage === 'vertex' ) {
  1254. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  1255. } else if ( shaderStage === 'fragment' ) {
  1256. if ( isOutputStruct ) {
  1257. stageData.returnType = outputNode.getNodeType( this );
  1258. stageData.structs += 'var<private> output : ' + stageData.returnType + ';';
  1259. flow += `return ${ flowSlotData.result };`;
  1260. } else {
  1261. let structSnippet = '\t@location(0) color: vec4<f32>';
  1262. const builtins = this.getBuiltins( 'output' );
  1263. if ( builtins ) structSnippet += ',\n\t' + builtins;
  1264. stageData.returnType = 'OutputStruct';
  1265. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  1266. stageData.structs += '\nvar<private> output : OutputStruct;';
  1267. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  1268. }
  1269. }
  1270. }
  1271. }
  1272. stageData.flow = flow;
  1273. }
  1274. this.shaderStage = null;
  1275. if ( this.material !== null ) {
  1276. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  1277. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  1278. } else {
  1279. // Early strictly validated in computeNode
  1280. const workgroupSize = this.object.workgroupSize;
  1281. this.computeShader = this._getWGSLComputeCode( shadersData.compute, workgroupSize );
  1282. }
  1283. }
  1284. /**
  1285. * Returns the native shader method name for a given generic name.
  1286. *
  1287. * @param {string} method - The method name to resolve.
  1288. * @param {?string} [output=null] - An optional output.
  1289. * @return {string} The resolved WGSL method name.
  1290. */
  1291. getMethod( method, output = null ) {
  1292. let wgslMethod;
  1293. if ( output !== null ) {
  1294. wgslMethod = this._getWGSLMethod( method + '_' + output );
  1295. }
  1296. if ( wgslMethod === undefined ) {
  1297. wgslMethod = this._getWGSLMethod( method );
  1298. }
  1299. return wgslMethod || method;
  1300. }
  1301. /**
  1302. * Returns the bitcast method name for a given input and outputType.
  1303. *
  1304. * @param {string} type - The output type to bitcast to.
  1305. * @return {string} The resolved WGSL bitcast invocation.
  1306. */
  1307. getBitcastMethod( type ) {
  1308. const dataType = this.getType( type );
  1309. return `bitcast<${ dataType }>`;
  1310. }
  1311. /**
  1312. * Returns the float packing method name for a given numeric encoding.
  1313. *
  1314. * @param {string} encoding - The numeric encoding that describes how the float values are mapped to the integer range.
  1315. * @returns {string} The resolve WGSL float packing method name.
  1316. */
  1317. getFloatPackingMethod( encoding ) {
  1318. return this.getMethod( `floatpack_${ encoding }_2x16` );
  1319. }
  1320. /**
  1321. * Returns the float unpacking method name for a given numeric encoding.
  1322. *
  1323. * @param {string} encoding - The numeric encoding that describes how the integer values are mapped to the float range.
  1324. * @returns {string} The resolve WGSL float unpacking method name.
  1325. */
  1326. getFloatUnpackingMethod( encoding ) {
  1327. return this.getMethod( `floatunpack_${ encoding }_2x16` );
  1328. }
  1329. /**
  1330. * Returns the native snippet for a ternary operation.
  1331. *
  1332. * @param {string} condSnippet - The condition determining which expression gets resolved.
  1333. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  1334. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  1335. * @return {string} The resolved method name.
  1336. */
  1337. getTernary( condSnippet, ifSnippet, elseSnippet ) {
  1338. return `select( ${elseSnippet}, ${ifSnippet}, ${condSnippet} )`;
  1339. }
  1340. /**
  1341. * Returns the WGSL type of the given node data type.
  1342. *
  1343. * @param {string} type - The node data type.
  1344. * @return {string} The WGSL type.
  1345. */
  1346. getType( type ) {
  1347. return wgslTypeLib[ type ] || type;
  1348. }
  1349. /**
  1350. * Whether the requested feature is available or not.
  1351. *
  1352. * @param {string} name - The requested feature.
  1353. * @return {boolean} Whether the requested feature is supported or not.
  1354. */
  1355. isAvailable( name ) {
  1356. let result = supports[ name ];
  1357. if ( result === undefined ) {
  1358. if ( name === 'float32Filterable' ) {
  1359. result = this.renderer.hasFeature( 'float32-filterable' );
  1360. } else if ( name === 'clipDistance' ) {
  1361. result = this.renderer.hasFeature( 'clip-distances' );
  1362. }
  1363. supports[ name ] = result;
  1364. }
  1365. return result;
  1366. }
  1367. /**
  1368. * Returns the native shader method name for a given generic name.
  1369. *
  1370. * @private
  1371. * @param {string} method - The method name to resolve.
  1372. * @return {string} The resolved WGSL method name.
  1373. */
  1374. _getWGSLMethod( method ) {
  1375. if ( wgslPolyfill[ method ] !== undefined ) {
  1376. this._include( method );
  1377. }
  1378. return wgslMethods[ method ];
  1379. }
  1380. /**
  1381. * Includes the given method name into the current
  1382. * function node.
  1383. *
  1384. * @private
  1385. * @param {string} name - The method name to include.
  1386. * @return {CodeNode} The respective code node.
  1387. */
  1388. _include( name ) {
  1389. const codeNode = wgslPolyfill[ name ];
  1390. codeNode.build( this );
  1391. this.addInclude( codeNode );
  1392. return codeNode;
  1393. }
  1394. /**
  1395. * Returns a WGSL vertex shader based on the given shader data.
  1396. *
  1397. * @private
  1398. * @param {Object} shaderData - The shader data.
  1399. * @return {string} The vertex shader.
  1400. */
  1401. _getWGSLVertexCode( shaderData ) {
  1402. return `${ this.getSignature() }
  1403. // directives
  1404. ${shaderData.directives}
  1405. // structs
  1406. ${shaderData.structs}
  1407. // uniforms
  1408. ${shaderData.uniforms}
  1409. // varyings
  1410. ${shaderData.varyings}
  1411. var<private> varyings : VaryingsStruct;
  1412. // codes
  1413. ${shaderData.codes}
  1414. @vertex
  1415. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  1416. // vars
  1417. ${shaderData.vars}
  1418. // flow
  1419. ${shaderData.flow}
  1420. return varyings;
  1421. }
  1422. `;
  1423. }
  1424. /**
  1425. * Returns a WGSL fragment shader based on the given shader data.
  1426. *
  1427. * @private
  1428. * @param {Object} shaderData - The shader data.
  1429. * @return {string} The vertex shader.
  1430. */
  1431. _getWGSLFragmentCode( shaderData ) {
  1432. return `${ this.getSignature() }
  1433. // global
  1434. ${ diagnostics }
  1435. // structs
  1436. ${shaderData.structs}
  1437. // uniforms
  1438. ${shaderData.uniforms}
  1439. // codes
  1440. ${shaderData.codes}
  1441. @fragment
  1442. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  1443. // vars
  1444. ${shaderData.vars}
  1445. // flow
  1446. ${shaderData.flow}
  1447. }
  1448. `;
  1449. }
  1450. /**
  1451. * Returns a WGSL compute shader based on the given shader data.
  1452. *
  1453. * @private
  1454. * @param {Object} shaderData - The shader data.
  1455. * @param {string} workgroupSize - The workgroup size.
  1456. * @return {string} The vertex shader.
  1457. */
  1458. _getWGSLComputeCode( shaderData, workgroupSize ) {
  1459. const [ workgroupSizeX, workgroupSizeY, workgroupSizeZ ] = workgroupSize;
  1460. return `${ this.getSignature() }
  1461. // directives
  1462. ${ shaderData.directives }
  1463. // system
  1464. var<private> instanceIndex : u32;
  1465. // locals
  1466. ${ shaderData.scopedArrays }
  1467. // structs
  1468. ${ shaderData.structs }
  1469. // uniforms
  1470. ${ shaderData.uniforms }
  1471. // codes
  1472. ${ shaderData.codes }
  1473. @compute @workgroup_size( ${ workgroupSizeX }, ${ workgroupSizeY }, ${ workgroupSizeZ } )
  1474. fn main( ${ shaderData.attributes } ) {
  1475. // system
  1476. instanceIndex = globalId.x
  1477. + globalId.y * ( ${ workgroupSizeX } * numWorkgroups.x )
  1478. + globalId.z * ( ${ workgroupSizeX } * numWorkgroups.x ) * ( ${ workgroupSizeY } * numWorkgroups.y );
  1479. // vars
  1480. ${ shaderData.vars }
  1481. // flow
  1482. ${ shaderData.flow }
  1483. }
  1484. `;
  1485. }
  1486. /**
  1487. * Returns a WGSL struct based on the given name and variables.
  1488. *
  1489. * @private
  1490. * @param {string} name - The struct name.
  1491. * @param {string} vars - The struct variables.
  1492. * @return {string} The WGSL snippet representing a struct.
  1493. */
  1494. _getWGSLStruct( name, vars ) {
  1495. return `
  1496. struct ${name} {
  1497. ${vars}
  1498. };`;
  1499. }
  1500. /**
  1501. * Returns a WGSL struct binding.
  1502. *
  1503. * @private
  1504. * @param {string} name - The struct name.
  1505. * @param {string} vars - The struct variables.
  1506. * @param {string} access - The access.
  1507. * @param {number} [binding=0] - The binding index.
  1508. * @param {number} [group=0] - The group index.
  1509. * @return {string} The WGSL snippet representing a struct binding.
  1510. */
  1511. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  1512. const structName = name + 'Struct';
  1513. const structSnippet = this._getWGSLStruct( structName, vars );
  1514. return `${structSnippet}
  1515. @binding( ${ binding } ) @group( ${ group } )
  1516. var<${access}> ${ name } : ${ structName };`;
  1517. }
  1518. }
  1519. export default WGSLNodeBuilder;
粤ICP备19079148号