lots-of-objects-morphtargets.html 12 KB

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