webgpu_materials.html 11 KB

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