webgpu_materials.html 12 KB

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