lots-of-objects-morphtargets-w-colors.html 15 KB

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