webgpu_materials.html 12 KB

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