webgl_instancing_scatter.html 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgl - instancing - scatter</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. <script type="module">
  11. import * as THREE from '../build/three.module.js';
  12. import { MeshSurfaceSampler } from './jsm/math/MeshSurfaceSampler.js';
  13. import { GLTFLoader } from './jsm/loaders/GLTFLoader.js';
  14. import Stats from './jsm/libs/stats.module.js';
  15. import { GUI } from './jsm/libs/dat.gui.module.js';
  16. let camera, scene, renderer, stats;
  17. const api = {
  18. count: 2000,
  19. distribution: 'random',
  20. resample: resample,
  21. surfaceColor: 0xFFF784,
  22. backgroundColor: 0xE39469,
  23. };
  24. let stemMesh, blossomMesh;
  25. let stemGeometry, blossomGeometry;
  26. let stemMaterial, blossomMaterial;
  27. let sampler;
  28. const count = api.count;
  29. const ages = new Float32Array( count );
  30. const scales = new Float32Array( count );
  31. const dummy = new THREE.Object3D();
  32. const _position = new THREE.Vector3();
  33. const _normal = new THREE.Vector3();
  34. const _scale = new THREE.Vector3();
  35. // let surfaceGeometry = new THREE.BoxGeometry( 10, 10, 10 ).toNonIndexed();
  36. const surfaceGeometry = new THREE.TorusKnotGeometry( 10, 3, 100, 16 ).toNonIndexed();
  37. const surfaceMaterial = new THREE.MeshLambertMaterial( { color: api.surfaceColor, wireframe: false } );
  38. const surface = new THREE.Mesh( surfaceGeometry, surfaceMaterial );
  39. // Source: https://gist.github.com/gre/1650294
  40. const easeOutCubic = function ( t ) {
  41. return ( -- t ) * t * t + 1;
  42. };
  43. // Scaling curve causes particles to grow quickly, ease gradually into full scale, then
  44. // disappear quickly. More of the particle's lifetime is spent around full scale.
  45. const scaleCurve = function ( t ) {
  46. return Math.abs( easeOutCubic( ( t > 0.5 ? 1 - t : t ) * 2 ) );
  47. };
  48. const loader = new GLTFLoader();
  49. loader.load( './models/gltf/Flower/Flower.glb', function ( gltf ) {
  50. const _stemMesh = gltf.scene.getObjectByName( 'Stem' );
  51. const _blossomMesh = gltf.scene.getObjectByName( 'Blossom' );
  52. stemGeometry = _stemMesh.geometry.clone();
  53. blossomGeometry = _blossomMesh.geometry.clone();
  54. const defaultTransform = new THREE.Matrix4()
  55. .makeRotationX( Math.PI )
  56. .multiply( new THREE.Matrix4().makeScale( 7, 7, 7 ) );
  57. stemGeometry.applyMatrix4( defaultTransform );
  58. blossomGeometry.applyMatrix4( defaultTransform );
  59. stemMaterial = _stemMesh.material;
  60. blossomMaterial = _blossomMesh.material;
  61. stemMesh = new THREE.InstancedMesh( stemGeometry, stemMaterial, count );
  62. blossomMesh = new THREE.InstancedMesh( blossomGeometry, blossomMaterial, count );
  63. // Assign random colors to the blossoms.
  64. const color = new THREE.Color();
  65. const blossomPalette = [ 0xF20587, 0xF2D479, 0xF2C879, 0xF2B077, 0xF24405 ];
  66. for ( let i = 0; i < count; i ++ ) {
  67. color.setHex( blossomPalette[ Math.floor( Math.random() * blossomPalette.length ) ] );
  68. blossomMesh.setColorAt( i, color );
  69. }
  70. // Instance matrices will be updated every frame.
  71. stemMesh.instanceMatrix.setUsage( THREE.DynamicDrawUsage );
  72. blossomMesh.instanceMatrix.setUsage( THREE.DynamicDrawUsage );
  73. resample();
  74. init();
  75. animate();
  76. } );
  77. function init() {
  78. camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 0.1, 100 );
  79. camera.position.set( 25, 25, 25 );
  80. camera.lookAt( 0, 0, 0 );
  81. //
  82. scene = new THREE.Scene();
  83. scene.background = new THREE.Color( api.backgroundColor );
  84. const pointLight = new THREE.PointLight( 0xAA8899, 0.75 );
  85. pointLight.position.set( 50, - 25, 75 );
  86. scene.add( pointLight );
  87. scene.add( new THREE.HemisphereLight() );
  88. //
  89. scene.add( stemMesh );
  90. scene.add( blossomMesh );
  91. scene.add( surface );
  92. //
  93. const gui = new GUI();
  94. gui.add( api, 'count', 0, count ).onChange( function () {
  95. stemMesh.count = api.count;
  96. blossomMesh.count = api.count;
  97. } );
  98. // gui.addColor( api, 'backgroundColor' ).onChange( function () {
  99. // scene.background.setHex( api.backgroundColor );
  100. // } );
  101. // gui.addColor( api, 'surfaceColor' ).onChange( function () {
  102. // surfaceMaterial.color.setHex( api.surfaceColor );
  103. // } );
  104. gui.add( api, 'distribution' ).options( [ 'random', 'weighted' ] ).onChange( resample );
  105. gui.add( api, 'resample' );
  106. //
  107. renderer = new THREE.WebGLRenderer( { antialias: true } );
  108. renderer.setPixelRatio( window.devicePixelRatio );
  109. renderer.setSize( window.innerWidth, window.innerHeight );
  110. document.body.appendChild( renderer.domElement );
  111. //
  112. stats = new Stats();
  113. document.body.appendChild( stats.dom );
  114. //
  115. window.addEventListener( 'resize', onWindowResize );
  116. }
  117. function resample() {
  118. const vertexCount = surface.geometry.getAttribute( 'position' ).count;
  119. console.info( 'Sampling ' + count + ' points from a surface with ' + vertexCount + ' vertices...' );
  120. //
  121. console.time( '.build()' );
  122. sampler = new MeshSurfaceSampler( surface )
  123. .setWeightAttribute( api.distribution === 'weighted' ? 'uv' : null )
  124. .build();
  125. console.timeEnd( '.build()' );
  126. //
  127. console.time( '.sample()' );
  128. for ( let i = 0; i < count; i ++ ) {
  129. ages[ i ] = Math.random();
  130. scales[ i ] = scaleCurve( ages[ i ] );
  131. resampleParticle( i );
  132. }
  133. console.timeEnd( '.sample()' );
  134. stemMesh.instanceMatrix.needsUpdate = true;
  135. blossomMesh.instanceMatrix.needsUpdate = true;
  136. }
  137. function resampleParticle( i ) {
  138. sampler.sample( _position, _normal );
  139. _normal.add( _position );
  140. dummy.position.copy( _position );
  141. dummy.scale.set( scales[ i ], scales[ i ], scales[ i ] );
  142. dummy.lookAt( _normal );
  143. dummy.updateMatrix();
  144. stemMesh.setMatrixAt( i, dummy.matrix );
  145. blossomMesh.setMatrixAt( i, dummy.matrix );
  146. }
  147. function updateParticle( i ) {
  148. // Update lifecycle.
  149. ages[ i ] += 0.005;
  150. if ( ages[ i ] >= 1 ) {
  151. ages[ i ] = 0.001;
  152. scales[ i ] = scaleCurve( ages[ i ] );
  153. resampleParticle( i );
  154. return;
  155. }
  156. // Update scale.
  157. const prevScale = scales[ i ];
  158. scales[ i ] = scaleCurve( ages[ i ] );
  159. _scale.set( scales[ i ] / prevScale, scales[ i ] / prevScale, scales[ i ] / prevScale );
  160. // Update transform.
  161. stemMesh.getMatrixAt( i, dummy.matrix );
  162. dummy.matrix.scale( _scale );
  163. stemMesh.setMatrixAt( i, dummy.matrix );
  164. blossomMesh.setMatrixAt( i, dummy.matrix );
  165. }
  166. function onWindowResize() {
  167. camera.aspect = window.innerWidth / window.innerHeight;
  168. camera.updateProjectionMatrix();
  169. renderer.setSize( window.innerWidth, window.innerHeight );
  170. }
  171. //
  172. function animate() {
  173. requestAnimationFrame( animate );
  174. render();
  175. stats.update();
  176. }
  177. function render() {
  178. if ( stemMesh && blossomMesh ) {
  179. const time = Date.now() * 0.001;
  180. scene.rotation.x = Math.sin( time / 4 );
  181. scene.rotation.y = Math.sin( time / 2 );
  182. for ( let i = 0; i < api.count; i ++ ) {
  183. updateParticle( i );
  184. }
  185. stemMesh.instanceMatrix.needsUpdate = true;
  186. blossomMesh.instanceMatrix.needsUpdate = true;
  187. }
  188. renderer.render( scene, camera );
  189. }
  190. </script>
  191. </body>
  192. </html>