lots-of-objects-morphtargets.html 12 KB

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