threejs-lots-of-objects-animated.html 12 KB

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