webgl_instancing_scatter.html 7.6 KB

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