webgpu_materials.html 12 KB

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