lots-of-objects-animated.html 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  1. <!-- Licensed under a BSD license. See license.html for license -->
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. <meta charset="utf-8">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
  7. <title>Three.js - Lots of Objects - Animated</title>
  8. <style>
  9. html, body {
  10. height: 100%;
  11. margin: 0;
  12. color: white;
  13. }
  14. #c {
  15. width: 100%;
  16. height: 100%;
  17. display: block;
  18. }
  19. #ui {
  20. position: absolute;
  21. left: 1em;
  22. top: 1em;
  23. }
  24. #ui>div {
  25. font-size: 20pt;
  26. padding: 1em;
  27. display: inline-block;
  28. }
  29. #ui>div.selected {
  30. color: red;
  31. }
  32. @media (max-width: 700px) {
  33. #ui>div {
  34. display: block;
  35. padding: .25em;
  36. }
  37. }
  38. </style>
  39. </head>
  40. <body>
  41. <canvas id="c"></canvas>
  42. <div id="ui"></div>
  43. </body>
  44. <script type="importmap">
  45. {
  46. "imports": {
  47. "three": "../../build/three.module.js",
  48. "three/addons/": "../../examples/jsm/"
  49. }
  50. }
  51. </script>
  52. <script type="module">
  53. import * as THREE from 'three';
  54. import * as BufferGeometryUtils from 'three/addons/utils/BufferGeometryUtils.js';
  55. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  56. import TWEEN from 'three/addons/libs/tween.module.js';
  57. class TweenManger {
  58. constructor() {
  59. this.numTweensRunning = 0;
  60. }
  61. _handleComplete() {
  62. -- this.numTweensRunning;
  63. console.assert( this.numTweensRunning >= 0 ); /* eslint no-console: off */
  64. }
  65. createTween( targetObject ) {
  66. const self = this;
  67. ++ this.numTweensRunning;
  68. let userCompleteFn = () => {};
  69. // create a new tween and install our own onComplete callback
  70. const tween = new TWEEN.Tween( targetObject ).onComplete( function ( ...args ) {
  71. self._handleComplete();
  72. userCompleteFn.call( this, ...args );
  73. } );
  74. // replace the tween's onComplete function with our own
  75. // so we can call the user's callback if they supply one.
  76. tween.onComplete = ( fn ) => {
  77. userCompleteFn = fn;
  78. return tween;
  79. };
  80. return tween;
  81. }
  82. update() {
  83. TWEEN.update();
  84. return this.numTweensRunning > 0;
  85. }
  86. }
  87. function main() {
  88. const canvas = document.querySelector( '#c' );
  89. const renderer = new THREE.WebGLRenderer( { antialias: true, canvas } );
  90. const tweenManager = new TweenManger();
  91. const fov = 60;
  92. const aspect = 2; // the canvas default
  93. const near = 0.1;
  94. const far = 10;
  95. const camera = new THREE.PerspectiveCamera( fov, aspect, near, far );
  96. camera.position.z = 2.5;
  97. const controls = new OrbitControls( camera, canvas );
  98. controls.enableDamping = true;
  99. controls.enablePan = false;
  100. controls.minDistance = 1.2;
  101. controls.maxDistance = 4;
  102. controls.update();
  103. const scene = new THREE.Scene();
  104. scene.background = new THREE.Color( 'black' );
  105. {
  106. const loader = new THREE.TextureLoader();
  107. const texture = loader.load( 'resources/images/world.jpg', render );
  108. texture.colorSpace = THREE.SRGBColorSpace;
  109. const geometry = new THREE.SphereGeometry( 1, 64, 32 );
  110. const material = new THREE.MeshBasicMaterial( { map: texture } );
  111. scene.add( new THREE.Mesh( geometry, material ) );
  112. }
  113. async function loadFile( url ) {
  114. const req = await fetch( url );
  115. return req.text();
  116. }
  117. function parseData( text ) {
  118. const data = [];
  119. const settings = { data };
  120. let max;
  121. let min;
  122. // split into lines
  123. text.split( '\n' ).forEach( ( line ) => {
  124. // split the line by whitespace
  125. const parts = line.trim().split( /\s+/ );
  126. if ( parts.length === 2 ) {
  127. // only 2 parts, must be a key/value pair
  128. settings[ parts[ 0 ] ] = parseFloat( parts[ 1 ] );
  129. } else if ( parts.length > 2 ) {
  130. // more than 2 parts, must be data
  131. const values = parts.map( ( v ) => {
  132. const value = parseFloat( v );
  133. if ( value === settings.NODATA_value ) {
  134. return undefined;
  135. }
  136. max = Math.max( max === undefined ? value : max, value );
  137. min = Math.min( min === undefined ? value : min, value );
  138. return value;
  139. } );
  140. data.push( values );
  141. }
  142. } );
  143. return Object.assign( settings, { min, max } );
  144. }
  145. function addBoxes( file, hueRange ) {
  146. const { min, max, data } = file;
  147. const range = max - min;
  148. // these helpers will make it easy to position the boxes
  149. // We can rotate the lon helper on its Y axis to the longitude
  150. const lonHelper = new THREE.Object3D();
  151. scene.add( lonHelper );
  152. // We rotate the latHelper on its X axis to the latitude
  153. const latHelper = new THREE.Object3D();
  154. lonHelper.add( latHelper );
  155. // The position helper moves the object to the edge of the sphere
  156. const positionHelper = new THREE.Object3D();
  157. positionHelper.position.z = 1;
  158. latHelper.add( positionHelper );
  159. // Used to move the center of the cube so it scales from the position Z axis
  160. const originHelper = new THREE.Object3D();
  161. originHelper.position.z = 0.5;
  162. positionHelper.add( originHelper );
  163. const color = new THREE.Color();
  164. const lonFudge = Math.PI * .5;
  165. const latFudge = Math.PI * - 0.135;
  166. const geometries = [];
  167. data.forEach( ( row, latNdx ) => {
  168. row.forEach( ( value, lonNdx ) => {
  169. if ( value === undefined ) {
  170. return;
  171. }
  172. const amount = ( value - min ) / range;
  173. const boxWidth = 1;
  174. const boxHeight = 1;
  175. const boxDepth = 1;
  176. const geometry = new THREE.BoxGeometry( boxWidth, boxHeight, boxDepth );
  177. // adjust the helpers to point to the latitude and longitude
  178. lonHelper.rotation.y = THREE.MathUtils.degToRad( lonNdx + file.xllcorner ) + lonFudge;
  179. latHelper.rotation.x = THREE.MathUtils.degToRad( latNdx + file.yllcorner ) + latFudge;
  180. // use the world matrix of the origin helper to
  181. // position this geometry
  182. positionHelper.scale.set( 0.005, 0.005, THREE.MathUtils.lerp( 0.01, 0.5, amount ) );
  183. originHelper.updateWorldMatrix( true, false );
  184. geometry.applyMatrix4( originHelper.matrixWorld );
  185. // compute a color
  186. const hue = THREE.MathUtils.lerp( ...hueRange, amount );
  187. const saturation = 1;
  188. const lightness = THREE.MathUtils.lerp( 0.4, 1.0, amount );
  189. color.setHSL( hue, saturation, lightness );
  190. // get the colors as an array of values from 0 to 255
  191. const rgb = color.toArray().map( v => v * 255 );
  192. // make an array to store colors for each vertex
  193. const numVerts = geometry.getAttribute( 'position' ).count;
  194. const itemSize = 3; // r, g, b
  195. const colors = new Uint8Array( itemSize * numVerts );
  196. // copy the color into the colors array for each vertex
  197. colors.forEach( ( v, ndx ) => {
  198. colors[ ndx ] = rgb[ ndx % 3 ];
  199. } );
  200. const normalized = true;
  201. const colorAttrib = new THREE.BufferAttribute( colors, itemSize, normalized );
  202. geometry.setAttribute( 'color', colorAttrib );
  203. geometries.push( geometry );
  204. } );
  205. } );
  206. const mergedGeometry = BufferGeometryUtils.mergeGeometries(
  207. geometries, false );
  208. const material = new THREE.MeshBasicMaterial( {
  209. vertexColors: true,
  210. transparent: true,
  211. opacity: 0,
  212. } );
  213. const mesh = new THREE.Mesh( mergedGeometry, material );
  214. scene.add( mesh );
  215. return mesh;
  216. }
  217. async function loadData( info ) {
  218. const text = await loadFile( info.url );
  219. info.file = parseData( text );
  220. }
  221. async function loadAll() {
  222. const fileInfos = [
  223. { name: 'men', hueRange: [ 0.7, 0.3 ], url: 'resources/data/gpw/gpw_v4_basic_demographic_characteristics_rev10_a000_014mt_2010_cntm_1_deg.asc' },
  224. { name: 'women', hueRange: [ 0.9, 1.1 ], url: 'resources/data/gpw/gpw_v4_basic_demographic_characteristics_rev10_a000_014ft_2010_cntm_1_deg.asc' },
  225. ];
  226. await Promise.all( fileInfos.map( loadData ) );
  227. function mapValues( data, fn ) {
  228. return data.map( ( row, rowNdx ) => {
  229. return row.map( ( value, colNdx ) => {
  230. return fn( value, rowNdx, colNdx );
  231. } );
  232. } );
  233. }
  234. function makeDiffFile( baseFile, otherFile, compareFn ) {
  235. let min;
  236. let max;
  237. const baseData = baseFile.data;
  238. const otherData = otherFile.data;
  239. const data = mapValues( baseData, ( base, rowNdx, colNdx ) => {
  240. const other = otherData[ rowNdx ][ colNdx ];
  241. if ( base === undefined || other === undefined ) {
  242. return undefined;
  243. }
  244. const value = compareFn( base, other );
  245. min = Math.min( min === undefined ? value : min, value );
  246. max = Math.max( max === undefined ? value : max, value );
  247. return value;
  248. } );
  249. // make a copy of baseFile and replace min, max, and data
  250. // with the new data
  251. return { ...baseFile, min, max, data };
  252. }
  253. // generate a new set of data
  254. {
  255. const menInfo = fileInfos[ 0 ];
  256. const womenInfo = fileInfos[ 1 ];
  257. const menFile = menInfo.file;
  258. const womenFile = womenInfo.file;
  259. function amountGreaterThan( a, b ) {
  260. return Math.max( a - b, 0 );
  261. }
  262. fileInfos.push( {
  263. name: '>50%men',
  264. hueRange: [ 0.6, 1.1 ],
  265. file: makeDiffFile( menFile, womenFile, ( men, women ) => {
  266. return amountGreaterThan( men, women );
  267. } ),
  268. } );
  269. fileInfos.push( {
  270. name: '>50% women',
  271. hueRange: [ 0.0, 0.4 ],
  272. file: makeDiffFile( womenFile, menFile, ( women, men ) => {
  273. return amountGreaterThan( women, men );
  274. } ),
  275. } );
  276. }
  277. function showFileInfo( fileInfos, fileInfo ) {
  278. fileInfos.forEach( ( info ) => {
  279. const durationInMs = 1000;
  280. const visible = fileInfo === info;
  281. // const scale = visible ? 1 : 0.1;
  282. const opacity = visible ? 1 : 0;
  283. info.elem.className = visible ? 'selected' : '';
  284. info.root.visible = visible || info.root.material.opacity > 0;
  285. tweenManager.createTween( info.root.material )
  286. .to( { opacity }, durationInMs )
  287. .start()
  288. .onComplete( () => {
  289. info.root.visible = visible;
  290. } );
  291. // tweenManager.createTween(info.root.material)
  292. // .to({depthWrite: visible}, 0)
  293. // .delay(durationInMs * .5)
  294. // .start();
  295. // tweenManager.createTween(info.root)
  296. // .to({visible}, 0)
  297. // .delay(durationInMs)
  298. // .start();
  299. // tweenManager.createTween(info.root.scale)
  300. // .to({x: scale, y: scale, z: scale}, durationInMs)
  301. // .start();
  302. } );
  303. requestRenderIfNotRequested();
  304. }
  305. const uiElem = document.querySelector( '#ui' );
  306. fileInfos.forEach( ( info ) => {
  307. const boxes = addBoxes( info.file, info.hueRange );
  308. info.root = boxes;
  309. // boxes.scale.set(0.1, 0.1, 0.1);
  310. const div = document.createElement( 'div' );
  311. info.elem = div;
  312. div.textContent = info.name;
  313. uiElem.appendChild( div );
  314. function show() {
  315. showFileInfo( fileInfos, info );
  316. }
  317. div.addEventListener( 'mouseover', show );
  318. div.addEventListener( 'touchstart', show );
  319. } );
  320. // show the first set of data
  321. showFileInfo( fileInfos, fileInfos[ 0 ] );
  322. }
  323. loadAll();
  324. function resizeRendererToDisplaySize( renderer ) {
  325. const canvas = renderer.domElement;
  326. const width = canvas.clientWidth;
  327. const height = canvas.clientHeight;
  328. const needResize = canvas.width !== width || canvas.height !== height;
  329. if ( needResize ) {
  330. renderer.setSize( width, height, false );
  331. }
  332. return needResize;
  333. }
  334. let renderRequested = false;
  335. function render() {
  336. renderRequested = undefined;
  337. if ( resizeRendererToDisplaySize( renderer ) ) {
  338. const canvas = renderer.domElement;
  339. camera.aspect = canvas.clientWidth / canvas.clientHeight;
  340. camera.updateProjectionMatrix();
  341. }
  342. if ( tweenManager.update() ) {
  343. requestRenderIfNotRequested();
  344. }
  345. controls.update();
  346. renderer.render( scene, camera );
  347. }
  348. render();
  349. function requestRenderIfNotRequested() {
  350. if ( ! renderRequested ) {
  351. renderRequested = true;
  352. requestAnimationFrame( render );
  353. }
  354. }
  355. controls.addEventListener( 'change', requestRenderIfNotRequested );
  356. window.addEventListener( 'resize', requestRenderIfNotRequested );
  357. }
  358. main();
  359. </script>
  360. </html>