webgpu_materials.html 12 KB

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