webgpu_materials.html 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js - WebGPU - Materials</title>
  5. <meta charset="utf-8">
  6. <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
  7. <link type="text/css" rel="stylesheet" href="main.css">
  8. </head>
  9. <body>
  10. <div id="info">
  11. <a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> WebGPU - Materials
  12. </div>
  13. <script async src="https://unpkg.com/[email protected]/dist/es-module-shims.js"></script>
  14. <script type="importmap">
  15. {
  16. "imports": {
  17. "three": "../build/three.module.js",
  18. "three/addons/": "./jsm/",
  19. "three/nodes": "./jsm/nodes/Nodes.js"
  20. }
  21. }
  22. </script>
  23. <script type="module">
  24. import * as THREE from 'three';
  25. import * as Nodes from 'three/nodes';
  26. import { tslFn, wgslFn, attribute, positionLocal, positionWorld, normalLocal, normalWorld, normalView, color, texture, uv, float, vec2, vec3, vec4, oscSine, triplanarTexture, viewportBottomLeft, js, string, global, loop, MeshBasicNodeMaterial, NodeObjectLoader } from 'three/nodes';
  27. import WebGPU from 'three/addons/capabilities/WebGPU.js';
  28. import WebGPURenderer from 'three/addons/renderers/webgpu/WebGPURenderer.js';
  29. import { TeapotGeometry } from 'three/addons/geometries/TeapotGeometry.js';
  30. import Stats from 'three/addons/libs/stats.module.js';
  31. let stats;
  32. let camera, scene, renderer;
  33. const objects = [], materials = [];
  34. init();
  35. function init() {
  36. if ( WebGPU.isAvailable() === false ) {
  37. document.body.appendChild( WebGPU.getErrorMessage() );
  38. throw new Error( 'No WebGPU support' );
  39. }
  40. const container = document.createElement( 'div' );
  41. document.body.appendChild( container );
  42. camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 2000 );
  43. camera.position.set( 0, 200, 800 );
  44. scene = new THREE.Scene();
  45. // Grid
  46. const helper = new THREE.GridHelper( 1000, 40, 0x303030, 0x303030 );
  47. helper.position.y = - 75;
  48. scene.add( helper );
  49. // Materials
  50. const textureLoader = new THREE.TextureLoader();
  51. const uvTexture = textureLoader.load( './textures/uv_grid_opengl.jpg' );
  52. uvTexture.wrapS = THREE.RepeatWrapping;
  53. uvTexture.wrapT = THREE.RepeatWrapping;
  54. const opacityTexture = textureLoader.load( './textures/alphaMap.jpg' );
  55. opacityTexture.wrapS = THREE.RepeatWrapping;
  56. opacityTexture.wrapT = THREE.RepeatWrapping;
  57. let material;
  58. //
  59. // BASIC
  60. //
  61. // PositionLocal
  62. material = new MeshBasicNodeMaterial();
  63. material.colorNode = positionLocal;
  64. materials.push( material );
  65. // PositionWorld
  66. material = new MeshBasicNodeMaterial();
  67. material.colorNode = positionWorld;
  68. materials.push( material );
  69. // NormalLocal
  70. material = new MeshBasicNodeMaterial();
  71. material.colorNode = normalLocal;
  72. materials.push( material );
  73. // NormalWorld
  74. material = new MeshBasicNodeMaterial();
  75. material.colorNode = normalWorld;
  76. materials.push( material );
  77. // NormalView
  78. material = new MeshBasicNodeMaterial();
  79. material.colorNode = normalView;
  80. materials.push( material );
  81. // Texture
  82. material = new MeshBasicNodeMaterial();
  83. material.colorNode = texture( uvTexture );
  84. materials.push( material );
  85. // Opacity
  86. material = new MeshBasicNodeMaterial();
  87. material.colorNode = color( 0x0099FF );
  88. material.opacityNode = texture( uvTexture );
  89. material.transparent = true;
  90. materials.push( material );
  91. // AlphaTest
  92. material = new MeshBasicNodeMaterial();
  93. material.colorNode = texture( uvTexture );
  94. material.opacityNode = texture( opacityTexture );
  95. material.alphaTestNode = 0.5;
  96. materials.push( material );
  97. // Normal
  98. material = new THREE.MeshNormalMaterial();
  99. material.opacity = .5;
  100. material.transparent = true;
  101. materials.push( material );
  102. //
  103. // ADVANCED
  104. //
  105. // Custom ShaderNode ( desaturate filter )
  106. const desaturateShaderNode = tslFn( ( input ) => {
  107. return vec3( 0.299, 0.587, 0.114 ).dot( input.color.xyz );
  108. } );
  109. material = new MeshBasicNodeMaterial();
  110. material.colorNode = desaturateShaderNode( { color: texture( uvTexture ) } );
  111. materials.push( material );
  112. // Custom ShaderNode(no inputs) > Approach 2
  113. const desaturateNoInputsShaderNode = tslFn( () => {
  114. return vec3( 0.299, 0.587, 0.114 ).dot( texture( uvTexture ).xyz );
  115. } );
  116. material = new MeshBasicNodeMaterial();
  117. material.colorNode = desaturateNoInputsShaderNode();
  118. materials.push( material );
  119. // Custom WGSL ( desaturate filter )
  120. const desaturateWGSLNode = wgslFn( `
  121. fn desaturate( color:vec3<f32> ) -> vec3<f32> {
  122. let lum = vec3<f32>( 0.299, 0.587, 0.114 );
  123. return vec3<f32>( dot( lum, color ) );
  124. }
  125. ` );
  126. material = new MeshBasicNodeMaterial();
  127. material.colorNode = desaturateWGSLNode( { color: texture( uvTexture ) } );
  128. materials.push( material );
  129. // Custom WGSL ( get texture from keywords )
  130. const getWGSLTextureSample = wgslFn( `
  131. fn getWGSLTextureSample( tex: texture_2d<f32>, tex_sampler: sampler, uv:vec2<f32> ) -> vec4<f32> {
  132. return textureSample( tex, tex_sampler, uv ) * vec4<f32>( 0.0, 1.0, 0.0, 1.0 );
  133. }
  134. ` );
  135. const textureNode = texture( uvTexture );
  136. //getWGSLTextureSample.keywords = { tex: textureNode, tex_sampler: sampler( textureNode ) };
  137. material = new MeshBasicNodeMaterial();
  138. material.colorNode = getWGSLTextureSample( { tex: textureNode, tex_sampler: textureNode, uv: uv() } );
  139. materials.push( material );
  140. // Triplanar Texture Mapping
  141. material = new MeshBasicNodeMaterial();
  142. material.colorNode = triplanarTexture( texture( uvTexture ), null, null, float( .01 ) );
  143. materials.push( material );
  144. // Screen Projection Texture
  145. material = new MeshBasicNodeMaterial();
  146. material.colorNode = texture( uvTexture, viewportBottomLeft );
  147. materials.push( material );
  148. // Loop
  149. material = new MeshBasicNodeMaterial();
  150. materials.push( material );
  151. const loopCount = 10;
  152. material.colorNode = loop( loopCount, ( { i }, stack ) => {
  153. const output = vec4().temp();
  154. const scale = oscSine().mul( .09 ); // just a value to test
  155. const scaleI = scale.mul( i );
  156. const scaleINeg = scaleI.negate();
  157. const leftUV = uv().add( vec2( scaleI, 0 ) );
  158. const rightUV = uv().add( vec2( scaleINeg, 0 ) );
  159. const topUV = uv().add( vec2( 0, scaleI ) );
  160. const bottomUV = uv().add( vec2( 0, scaleINeg ) );
  161. stack.assign( output, output.add( texture( uvTexture, leftUV ) ) );
  162. stack.assign( output, output.add( texture( uvTexture, rightUV ) ) );
  163. stack.assign( output, output.add( texture( uvTexture, topUV ) ) );
  164. stack.assign( output, output.add( texture( uvTexture, bottomUV ) ) );
  165. return output.div( loopCount * 4 );
  166. } );
  167. // Scriptable
  168. global.set( 'THREE', THREE );
  169. global.set( 'TSL', Nodes );
  170. const asyncNode = js( `
  171. layout = {
  172. outputType: 'node'
  173. };
  174. const { float } = TSL;
  175. function init() {
  176. setTimeout( () => {
  177. local.set( 'result', float( 1.0 ) );
  178. refresh(); // refresh the node
  179. }, 1000 );
  180. return float( 0.0 );
  181. }
  182. function main() {
  183. const result = local.get( 'result', init );
  184. //console.log( 'result', result );
  185. return result;
  186. }
  187. ` ).scriptable();
  188. const scriptableNode = js( `
  189. layout = {
  190. outputType: 'node',
  191. elements: [
  192. { name: 'source', inputType: 'node' },
  193. { name: 'contrast', inputType: 'node' },
  194. { name: 'vector3', inputType: 'Vector3' },
  195. { name: 'message', inputType: 'string' },
  196. { name: 'binary', inputType: 'ArrayBuffer' },
  197. { name: 'object3d', inputType: 'Object3D' },
  198. { name: 'execFrom', inputType: 'string' }
  199. ]
  200. };
  201. const { saturation, float, oscSine, mul } = TSL;
  202. function helloWorld() {
  203. console.log( "Hello World!" );
  204. }
  205. function main() {
  206. const source = parameters.get( 'source' ) || float();
  207. const contrast = parameters.get( 'contrast' ) || float();
  208. const material = local.get( 'material' );
  209. //console.log( 'vector3', parameters.get( 'vector3' ) );
  210. if ( parameters.get( 'execFrom' ) === 'serialized' ) {
  211. //console.log( 'message', parameters.get( 'message' ).value );
  212. //console.log( 'binary', parameters.get( 'binary' ) );
  213. //console.log( 'object3d', parameters.get( 'object3d' ) ); // unserializable yet
  214. //console.log( global.get( 'renderer' ) );
  215. }
  216. if ( material ) material.needsUpdate = true;
  217. return mul( saturation( source, oscSine() ), contrast );
  218. }
  219. output = { helloWorld };
  220. ` ).scriptable();
  221. scriptableNode.setParameter( 'source', texture( uvTexture ).xyz );
  222. scriptableNode.setParameter( 'contrast', asyncNode );
  223. scriptableNode.setParameter( 'vector3', vec3( new THREE.Vector3( 1, 1, 1 ) ) );
  224. scriptableNode.setParameter( 'message', string( 'Hello World!' ) );
  225. scriptableNode.setParameter( 'binary', new ArrayBuffer( 4 ) );
  226. scriptableNode.setParameter( 'object3d', new THREE.Group() );
  227. scriptableNode.call( 'helloWorld' );
  228. material = new MeshBasicNodeMaterial();
  229. material.colorNode = scriptableNode;
  230. materials.push( material );
  231. scriptableNode.setLocal( 'material', material );
  232. //
  233. // Geometry
  234. //
  235. const geometry = new TeapotGeometry( 50, 18 );
  236. for ( let i = 0, l = materials.length; i < l; i ++ ) {
  237. addMesh( geometry, materials[ i ] );
  238. }
  239. const serializeMesh = scene.children[ scene.children.length - 1 ];
  240. //
  241. renderer = new WebGPURenderer( { antialias: true } );
  242. renderer.setPixelRatio( window.devicePixelRatio );
  243. renderer.setSize( window.innerWidth, window.innerHeight );
  244. renderer.setAnimationLoop( animate );
  245. container.appendChild( renderer.domElement );
  246. //
  247. stats = new Stats();
  248. container.appendChild( stats.dom );
  249. //
  250. window.addEventListener( 'resize', onWindowResize );
  251. //
  252. setTimeout( () => testSerialization( serializeMesh ), 1000 );
  253. }
  254. function addMesh( geometry, material ) {
  255. const mesh = new THREE.Mesh( geometry, material );
  256. mesh.position.x = ( objects.length % 4 ) * 200 - 400;
  257. mesh.position.z = Math.floor( objects.length / 4 ) * 200 - 200;
  258. mesh.rotation.x = Math.random() * 200 - 100;
  259. mesh.rotation.y = Math.random() * 200 - 100;
  260. mesh.rotation.z = Math.random() * 200 - 100;
  261. objects.push( mesh );
  262. scene.add( mesh );
  263. }
  264. function testSerialization( mesh ) {
  265. const json = mesh.toJSON();
  266. const loader = new NodeObjectLoader();
  267. const serializedMesh = loader.parse( json );
  268. serializedMesh.position.x = ( objects.length % 4 ) * 200 - 400;
  269. serializedMesh.position.z = Math.floor( objects.length / 4 ) * 200 - 200;
  270. const scriptableNode = serializedMesh.material.colorNode;
  271. // it's because local.get( 'material' ) is used in the example ( local/global is unserializable )
  272. scriptableNode.setLocal( 'material', serializedMesh.material );
  273. scriptableNode.setParameter( 'execFrom', 'serialized' );
  274. objects.push( serializedMesh );
  275. scene.add( serializedMesh );
  276. }
  277. function onWindowResize() {
  278. camera.aspect = window.innerWidth / window.innerHeight;
  279. camera.updateProjectionMatrix();
  280. renderer.setSize( window.innerWidth, window.innerHeight );
  281. }
  282. //
  283. function animate() {
  284. const timer = 0.0001 * Date.now();
  285. camera.position.x = Math.cos( timer ) * 1000;
  286. camera.position.z = Math.sin( timer ) * 1000;
  287. camera.lookAt( scene.position );
  288. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  289. const object = objects[ i ];
  290. object.rotation.x += 0.01;
  291. object.rotation.y += 0.005;
  292. }
  293. renderer.render( scene, camera );
  294. stats.update();
  295. }
  296. </script>
  297. </body>
  298. </html>