optimize-lots-of-objects-animated.html 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681
  1. <!DOCTYPE html><html lang="en"><head>
  2. <meta charset="utf-8">
  3. <title>Optimize Lots of Objects Animated</title>
  4. <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
  5. <meta name="twitter:card" content="summary_large_image">
  6. <meta name="twitter:site" content="@threejs">
  7. <meta name="twitter:title" content="Three.js – Optimize Lots of Objects Animated">
  8. <meta property="og:image" content="https://threejs.org/files/share.png">
  9. <link rel="shortcut icon" href="/files/favicon_white.ico" media="(prefers-color-scheme: dark)">
  10. <link rel="shortcut icon" href="/files/favicon.ico" media="(prefers-color-scheme: light)">
  11. <link rel="stylesheet" href="/manual/resources/lesson.css">
  12. <link rel="stylesheet" href="/manual/resources/lang.css">
  13. </head>
  14. <body>
  15. <div class="container">
  16. <div class="lesson-title">
  17. <h1>Optimize Lots of Objects Animated</h1>
  18. </div>
  19. <div class="lesson">
  20. <div class="lesson-main">
  21. <p>This article is a continuation of <a href="optimize-lots-of-objects.html">an article about optimizing lots of objects
  22. </a>. If you haven't read that
  23. yet please read it before proceeding. </p>
  24. <p>In the previous article we merged around 19000 cubes into a
  25. single geometry. This had the advantage that it optimized our drawing
  26. of 19000 cubes but it had the disadvantage of make it harder to
  27. move any individual cube.</p>
  28. <p>Depending on what we are trying to accomplish there are different solutions.
  29. In this case let's graph multiple sets of data and animate between the sets.</p>
  30. <p>The first thing we need to do is get multiple sets of data. Ideally we'd
  31. probably pre-process data offline but in this case let's load 2 sets of
  32. data and generate 2 more</p>
  33. <p>Here's our old loading code</p>
  34. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">loadFile('resources/data/gpw/gpw_v4_basic_demographic_characteristics_rev10_a000_014mt_2010_cntm_1_deg.asc')
  35. .then(parseData)
  36. .then(addBoxes)
  37. .then(render);
  38. </pre>
  39. <p>Let's change it to something like this</p>
  40. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">async function loadData(info) {
  41. const text = await loadFile(info.url);
  42. info.file = parseData(text);
  43. }
  44. async function loadAll() {
  45. const fileInfos = [
  46. {name: 'men', hueRange: [0.7, 0.3], url: 'resources/data/gpw/gpw_v4_basic_demographic_characteristics_rev10_a000_014mt_2010_cntm_1_deg.asc' },
  47. {name: 'women', hueRange: [0.9, 1.1], url: 'resources/data/gpw/gpw_v4_basic_demographic_characteristics_rev10_a000_014ft_2010_cntm_1_deg.asc' },
  48. ];
  49. await Promise.all(fileInfos.map(loadData));
  50. ...
  51. }
  52. loadAll();
  53. </pre>
  54. <p>The code above will load all the files in <code class="notranslate" translate="no">fileInfos</code> and when done each object
  55. in <code class="notranslate" translate="no">fileInfos</code> will have a <code class="notranslate" translate="no">file</code> property with the loaded file. <code class="notranslate" translate="no">name</code> and <code class="notranslate" translate="no">hueRange</code>
  56. we'll use later. <code class="notranslate" translate="no">name</code> will be for a UI field. <code class="notranslate" translate="no">hueRange</code> will be used to
  57. choose a range of hues to map over.</p>
  58. <p>The two files above are apparently the number of men per area and the number of
  59. women per area as of 2010. Note, I have no idea if this data is correct but
  60. it's not important really. The important part is showing different sets
  61. of data.</p>
  62. <p>Let's generate 2 more sets of data. One being the places where the number
  63. men are greater than the number of women and visa versa, the places where
  64. the number of women are greater than the number of men. </p>
  65. <p>The first thing let's write a function that given a 2 dimensional array of
  66. of arrays like we had before will map over it to generate a new 2 dimensional
  67. array of arrays</p>
  68. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">function mapValues(data, fn) {
  69. return data.map((row, rowNdx) =&gt; {
  70. return row.map((value, colNdx) =&gt; {
  71. return fn(value, rowNdx, colNdx);
  72. });
  73. });
  74. }
  75. </pre>
  76. <p>Like the normal <code class="notranslate" translate="no">Array.map</code> function the <code class="notranslate" translate="no">mapValues</code> function calls a function
  77. <code class="notranslate" translate="no">fn</code> for each value in the array of arrays. It passes it the value and both the
  78. row and column indices.</p>
  79. <p>Now let's make some code to generate a new file that is a comparison between 2
  80. files</p>
  81. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">function makeDiffFile(baseFile, otherFile, compareFn) {
  82. let min;
  83. let max;
  84. const baseData = baseFile.data;
  85. const otherData = otherFile.data;
  86. const data = mapValues(baseData, (base, rowNdx, colNdx) =&gt; {
  87. const other = otherData[rowNdx][colNdx];
  88. if (base === undefined || other === undefined) {
  89. return undefined;
  90. }
  91. const value = compareFn(base, other);
  92. min = Math.min(min === undefined ? value : min, value);
  93. max = Math.max(max === undefined ? value : max, value);
  94. return value;
  95. });
  96. // make a copy of baseFile and replace min, max, and data
  97. // with the new data
  98. return {...baseFile, min, max, data};
  99. }
  100. </pre>
  101. <p>The code above uses <code class="notranslate" translate="no">mapValues</code> to generate a new set of data that is
  102. a comparison based on the <code class="notranslate" translate="no">compareFn</code> function passed in. It also tracks
  103. the <code class="notranslate" translate="no">min</code> and <code class="notranslate" translate="no">max</code> comparison results. Finally it makes a new file with
  104. all the same properties as <code class="notranslate" translate="no">baseFile</code> except with a new <code class="notranslate" translate="no">min</code>, <code class="notranslate" translate="no">max</code> and <code class="notranslate" translate="no">data</code>.</p>
  105. <p>Then let's use that to make 2 new sets of data</p>
  106. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">{
  107. const menInfo = fileInfos[0];
  108. const womenInfo = fileInfos[1];
  109. const menFile = menInfo.file;
  110. const womenFile = womenInfo.file;
  111. function amountGreaterThan(a, b) {
  112. return Math.max(a - b, 0);
  113. }
  114. fileInfos.push({
  115. name: '&gt;50%men',
  116. hueRange: [0.6, 1.1],
  117. file: makeDiffFile(menFile, womenFile, (men, women) =&gt; {
  118. return amountGreaterThan(men, women);
  119. }),
  120. });
  121. fileInfos.push({
  122. name: '&gt;50% women',
  123. hueRange: [0.0, 0.4],
  124. file: makeDiffFile(womenFile, menFile, (women, men) =&gt; {
  125. return amountGreaterThan(women, men);
  126. }),
  127. });
  128. }
  129. </pre>
  130. <p>Now let's generate a UI to select between these sets of data. First we need
  131. some UI html</p>
  132. <pre class="prettyprint showlinemods notranslate lang-html" translate="no">&lt;body&gt;
  133. &lt;canvas id="c"&gt;&lt;/canvas&gt;
  134. + &lt;div id="ui"&gt;&lt;/div&gt;
  135. &lt;/body&gt;
  136. </pre>
  137. <p>and some CSS to make it appear in the top left area</p>
  138. <pre class="prettyprint showlinemods notranslate lang-css" translate="no">#ui {
  139. position: absolute;
  140. left: 1em;
  141. top: 1em;
  142. }
  143. #ui&gt;div {
  144. font-size: 20pt;
  145. padding: 1em;
  146. display: inline-block;
  147. }
  148. #ui&gt;div.selected {
  149. color: red;
  150. }
  151. </pre>
  152. <p>Then we can go over each file and generate a set of merged boxes per
  153. set of data and an element which when hovered over will show that set
  154. and hide all others.</p>
  155. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">// show the selected data, hide the rest
  156. function showFileInfo(fileInfos, fileInfo) {
  157. fileInfos.forEach((info) =&gt; {
  158. const visible = fileInfo === info;
  159. info.root.visible = visible;
  160. info.elem.className = visible ? 'selected' : '';
  161. });
  162. requestRenderIfNotRequested();
  163. }
  164. const uiElem = document.querySelector('#ui');
  165. fileInfos.forEach((info) =&gt; {
  166. const boxes = addBoxes(info.file, info.hueRange);
  167. info.root = boxes;
  168. const div = document.createElement('div');
  169. info.elem = div;
  170. div.textContent = info.name;
  171. uiElem.appendChild(div);
  172. div.addEventListener('mouseover', () =&gt; {
  173. showFileInfo(fileInfos, info);
  174. });
  175. });
  176. // show the first set of data
  177. showFileInfo(fileInfos, fileInfos[0]);
  178. </pre>
  179. <p>The one more change we need from the previous example is we need to make
  180. <code class="notranslate" translate="no">addBoxes</code> take a <code class="notranslate" translate="no">hueRange</code></p>
  181. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">-function addBoxes(file) {
  182. +function addBoxes(file, hueRange) {
  183. ...
  184. // compute a color
  185. - const hue = THREE.MathUtils.lerp(0.7, 0.3, amount);
  186. + const hue = THREE.MathUtils.lerp(...hueRange, amount);
  187. ...
  188. </pre>
  189. <p>and with that we should be able to show 4 sets of data. Hover the mouse over the labels
  190. or touch them to switch sets</p>
  191. <p></p><div translate="no" class="threejs_example_container notranslate">
  192. <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/lots-of-objects-multiple-data-sets.html"></iframe></div>
  193. <a class="threejs_center" href="/manual/examples/lots-of-objects-multiple-data-sets.html" target="_blank">click here to open in a separate window</a>
  194. </div>
  195. <p></p>
  196. <p>Note, there are a few strange data points that really stick out. I wonder what's up
  197. with those!??! In any case how do we animate between these 4 sets of data.</p>
  198. <p>Lots of ideas.</p>
  199. <ul>
  200. <li><p>Just fade between them using <a href="/docs/#api/en/materials/Material.opacity"><code class="notranslate" translate="no">Material.opacity</code></a></p>
  201. <p>The problem with this solution is the cubes perfectly overlap which
  202. means there will be z-fighting issues. It's possible we could fix
  203. that by changing the depth function and using blending. We should
  204. probably look into it.</p>
  205. </li>
  206. <li><p>Scale up the set we want to see and scale down the other sets</p>
  207. <p>Because all the boxes have their origin at the center of the planet
  208. if we scale them below 1.0 they will sink into the planet. At first that
  209. sounds like a good idea but the issue is all the low height boxes
  210. will disappear almost immediately and not be replaced until the new
  211. data set scales up to 1.0. This makes the transition not very pleasant.
  212. We could maybe fix that with a fancy custom shader.</p>
  213. </li>
  214. <li><p>Use Morphtargets</p>
  215. <p>Morphtargets are a way were we supply multiple values for each vertex
  216. in the geometry and <em>morph</em> or lerp (linear interpolate) between them.
  217. Morphtargets are most commonly used for facial animation of 3D characters
  218. but that's not their only use.</p>
  219. </li>
  220. </ul>
  221. <p>Let's try morphtargets.</p>
  222. <p>We'll still make a geometry for each set of data but we'll then extract
  223. the <code class="notranslate" translate="no">position</code> attribute from each one and use them as morphtargets.</p>
  224. <p>First let's change <code class="notranslate" translate="no">addBoxes</code> to just make and return the merged geometry.</p>
  225. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">-function addBoxes(file, hueRange) {
  226. +function makeBoxes(file, hueRange) {
  227. const {min, max, data} = file;
  228. const range = max - min;
  229. ...
  230. - const mergedGeometry = BufferGeometryUtils.mergeBufferGeometries(
  231. - geometries, false);
  232. - const material = new THREE.MeshBasicMaterial({
  233. - vertexColors: true,
  234. - });
  235. - const mesh = new THREE.Mesh(mergedGeometry, material);
  236. - scene.add(mesh);
  237. - return mesh;
  238. + return BufferGeometryUtils.mergeBufferGeometries(
  239. + geometries, false);
  240. }
  241. </pre>
  242. <p>There's one more thing we need to do here though. Morphtargets are required to
  243. all have exactly the same number of vertices. Vertex #123 in one target needs
  244. have a corresponding Vertex #123 in all other targets. But, as it is now
  245. different data sets might have some data points with no data so no box will be
  246. generated for that point which would mean no corresponding vertices for another
  247. set. So, we need to check across all data sets and either always generate
  248. something if there is data in any set or, generate nothing if there is data
  249. missing in any set. Let's do the latter.</p>
  250. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">+function dataMissingInAnySet(fileInfos, latNdx, lonNdx) {
  251. + for (const fileInfo of fileInfos) {
  252. + if (fileInfo.file.data[latNdx][lonNdx] === undefined) {
  253. + return true;
  254. + }
  255. + }
  256. + return false;
  257. +}
  258. -function makeBoxes(file, hueRange) {
  259. +function makeBoxes(file, hueRange, fileInfos) {
  260. const {min, max, data} = file;
  261. const range = max - min;
  262. ...
  263. const geometries = [];
  264. data.forEach((row, latNdx) =&gt; {
  265. row.forEach((value, lonNdx) =&gt; {
  266. + if (dataMissingInAnySet(fileInfos, latNdx, lonNdx)) {
  267. + return;
  268. + }
  269. const amount = (value - min) / range;
  270. ...
  271. </pre>
  272. <p>Now we'll change the code that was calling <code class="notranslate" translate="no">addBoxes</code> to use <code class="notranslate" translate="no">makeBoxes</code>
  273. and setup morphtargets</p>
  274. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">+// make geometry for each data set
  275. +const geometries = fileInfos.map((info) =&gt; {
  276. + return makeBoxes(info.file, info.hueRange, fileInfos);
  277. +});
  278. +
  279. +// use the first geometry as the base
  280. +// and add all the geometries as morphtargets
  281. +const baseGeometry = geometries[0];
  282. +baseGeometry.morphAttributes.position = geometries.map((geometry, ndx) =&gt; {
  283. + const attribute = geometry.getAttribute('position');
  284. + const name = `target${ndx}`;
  285. + attribute.name = name;
  286. + return attribute;
  287. +});
  288. +const material = new THREE.MeshBasicMaterial({
  289. + vertexColors: true,
  290. +});
  291. +const mesh = new THREE.Mesh(baseGeometry, material);
  292. +scene.add(mesh);
  293. const uiElem = document.querySelector('#ui');
  294. fileInfos.forEach((info) =&gt; {
  295. - const boxes = addBoxes(info.file, info.hueRange);
  296. - info.root = boxes;
  297. const div = document.createElement('div');
  298. info.elem = div;
  299. div.textContent = info.name;
  300. uiElem.appendChild(div);
  301. function show() {
  302. showFileInfo(fileInfos, info);
  303. }
  304. div.addEventListener('mouseover', show);
  305. div.addEventListener('touchstart', show);
  306. });
  307. // show the first set of data
  308. showFileInfo(fileInfos, fileInfos[0]);
  309. </pre>
  310. <p>Above we make geometry for each data set, use the first one as the base,
  311. then get a <code class="notranslate" translate="no">position</code> attribute from each geometry and add it as
  312. a morphtarget to the base geometry for <code class="notranslate" translate="no">position</code>.</p>
  313. <p>Now we need to change how we're showing and hiding the various data sets.
  314. Instead of showing or hiding a mesh we need to change the influence of the
  315. morphtargets. For the data set we want to see we need to have an influence of 1
  316. and for all the ones we don't want to see to we need to have an influence of 0.</p>
  317. <p>We could just set them to 0 or 1 directly but if we did that we wouldn't see any
  318. animation, it would just snap which would be no different than what we already
  319. have. We could also write some custom animation code which would be easy but
  320. because the original webgl globe uses
  321. <a href="https://github.com/tweenjs/tween.js/">an animation library</a> let's use the same one here.</p>
  322. <p>We need to include the library</p>
  323. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">import * as THREE from '/build/three.module.js';
  324. import * as BufferGeometryUtils from '/examples/jsm/utils/BufferGeometryUtils.js';
  325. import {OrbitControls} from '/examples/jsm/controls/OrbitControls.js';
  326. +import {TWEEN} from '/examples/jsm/libs/tween.min.js';
  327. </pre>
  328. <p>And then create a <code class="notranslate" translate="no">Tween</code> to animate the influences.</p>
  329. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">// show the selected data, hide the rest
  330. function showFileInfo(fileInfos, fileInfo) {
  331. + const targets = {};
  332. - fileInfos.forEach((info) =&gt; {
  333. + fileInfos.forEach((info, i) =&gt; {
  334. const visible = fileInfo === info;
  335. - info.root.visible = visible;
  336. info.elem.className = visible ? 'selected' : '';
  337. + targets[i] = visible ? 1 : 0;
  338. });
  339. + const durationInMs = 1000;
  340. + new TWEEN.Tween(mesh.morphTargetInfluences)
  341. + .to(targets, durationInMs)
  342. + .start();
  343. requestRenderIfNotRequested();
  344. }
  345. </pre>
  346. <p>We're also suppose to call <code class="notranslate" translate="no">TWEEN.update</code> every frame inside our render loop
  347. but that points out a problem. "tween.js" is designed for continuous rendering
  348. but we are <a href="rendering-on-demand.html">rendering on demand</a>. We could
  349. switch to continuous rendering but it's sometimes nice to only render on demand
  350. as it well stop using the user's power when nothing is happening
  351. so let's see if we can make it animate on demand.</p>
  352. <p>We'll make a <code class="notranslate" translate="no">TweenManager</code> to help. We'll use it to create the <code class="notranslate" translate="no">Tween</code>s and
  353. track them. It will have an <code class="notranslate" translate="no">update</code> method that will return <code class="notranslate" translate="no">true</code>
  354. if we need to call it again and <code class="notranslate" translate="no">false</code> if all the animations are finished.</p>
  355. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">class TweenManger {
  356. constructor() {
  357. this.numTweensRunning = 0;
  358. }
  359. _handleComplete() {
  360. --this.numTweensRunning;
  361. console.assert(this.numTweensRunning &gt;= 0);
  362. }
  363. createTween(targetObject) {
  364. const self = this;
  365. ++this.numTweensRunning;
  366. let userCompleteFn = () =&gt; {};
  367. // create a new tween and install our own onComplete callback
  368. const tween = new TWEEN.Tween(targetObject).onComplete(function(...args) {
  369. self._handleComplete();
  370. userCompleteFn.call(this, ...args);
  371. });
  372. // replace the tween's onComplete function with our own
  373. // so we can call the user's callback if they supply one.
  374. tween.onComplete = (fn) =&gt; {
  375. userCompleteFn = fn;
  376. return tween;
  377. };
  378. return tween;
  379. }
  380. update() {
  381. TWEEN.update();
  382. return this.numTweensRunning &gt; 0;
  383. }
  384. }
  385. </pre>
  386. <p>To use it we'll create one </p>
  387. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">function main() {
  388. const canvas = document.querySelector('#c');
  389. const renderer = new THREE.WebGLRenderer({canvas});
  390. + const tweenManager = new TweenManger();
  391. ...
  392. </pre>
  393. <p>We'll use it to create our <code class="notranslate" translate="no">Tween</code>s.</p>
  394. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">// show the selected data, hide the rest
  395. function showFileInfo(fileInfos, fileInfo) {
  396. const targets = {};
  397. fileInfos.forEach((info, i) =&gt; {
  398. const visible = fileInfo === info;
  399. info.elem.className = visible ? 'selected' : '';
  400. targets[i] = visible ? 1 : 0;
  401. });
  402. const durationInMs = 1000;
  403. - new TWEEN.Tween(mesh.morphTargetInfluences)
  404. + tweenManager.createTween(mesh.morphTargetInfluences)
  405. .to(targets, durationInMs)
  406. .start();
  407. requestRenderIfNotRequested();
  408. }
  409. </pre>
  410. <p>Then we'll update our render loop to update the tweens and keep rendering
  411. if there are still animations running.</p>
  412. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">function render() {
  413. renderRequested = false;
  414. if (resizeRendererToDisplaySize(renderer)) {
  415. const canvas = renderer.domElement;
  416. camera.aspect = canvas.clientWidth / canvas.clientHeight;
  417. camera.updateProjectionMatrix();
  418. }
  419. + if (tweenManager.update()) {
  420. + requestRenderIfNotRequested();
  421. + }
  422. controls.update();
  423. renderer.render(scene, camera);
  424. }
  425. render();
  426. </pre>
  427. <p>And with that we should be animating between data sets.</p>
  428. <p></p><div translate="no" class="threejs_example_container notranslate">
  429. <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/lots-of-objects-morphtargets.html"></iframe></div>
  430. <a class="threejs_center" href="/manual/examples/lots-of-objects-morphtargets.html" target="_blank">click here to open in a separate window</a>
  431. </div>
  432. <p></p>
  433. <p>That seems to work but unfortunately we lost the colors.</p>
  434. <p>Three.js does not support morphtarget colors and in fact this is an issue
  435. with the original <a href="https://github.com/dataarts/webgl-globe">webgl globe</a>.
  436. Basically it just makes colors for the first data set. Any other datasets
  437. use the same colors even if they are vastly different.</p>
  438. <p>Let's see if we can add support for morphing the colors. This might
  439. be brittle. The least brittle way would probably be to 100% write our own
  440. shaders but I think it would be useful to see how to modify the built
  441. in shaders.</p>
  442. <p>The first thing we need to do is make the code extract color a <a href="/docs/#api/en/core/BufferAttribute"><code class="notranslate" translate="no">BufferAttribute</code></a> from
  443. each data set's geometry.</p>
  444. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">// use the first geometry as the base
  445. // and add all the geometries as morphtargets
  446. const baseGeometry = geometries[0];
  447. baseGeometry.morphAttributes.position = geometries.map((geometry, ndx) =&gt; {
  448. const attribute = geometry.getAttribute('position');
  449. const name = `target${ndx}`;
  450. attribute.name = name;
  451. return attribute;
  452. });
  453. +const colorAttributes = geometries.map((geometry, ndx) =&gt; {
  454. + const attribute = geometry.getAttribute('color');
  455. + const name = `morphColor${ndx}`;
  456. + attribute.name = `color${ndx}`; // just for debugging
  457. + return {name, attribute};
  458. +});
  459. const material = new THREE.MeshBasicMaterial({
  460. vertexColors: true,
  461. });
  462. </pre>
  463. <p>We then need to modify the three.js shader. Three.js materials have an
  464. <a href="/docs/#api/en/materials/Material.onBeforeCompile"><code class="notranslate" translate="no">Material.onBeforeCompile</code></a> property we can assign a function. It gives us a
  465. chance to modify the material's shader before it is passed to WebGL. In fact the
  466. shader that is provided is actually a special three.js only syntax of shader
  467. that lists a bunch of shader <em>chunks</em> that three.js will substitute with the
  468. actual GLSL code for each chunk. Here is what the unmodified vertex shader code
  469. looks like as passed to <code class="notranslate" translate="no">onBeforeCompile</code>.</p>
  470. <pre class="prettyprint showlinemods notranslate lang-glsl" translate="no">#include &lt;common&gt;
  471. #include &lt;uv_pars_vertex&gt;
  472. #include &lt;uv2_pars_vertex&gt;
  473. #include &lt;envmap_pars_vertex&gt;
  474. #include &lt;color_pars_vertex&gt;
  475. #include &lt;fog_pars_vertex&gt;
  476. #include &lt;morphtarget_pars_vertex&gt;
  477. #include &lt;skinning_pars_vertex&gt;
  478. #include &lt;logdepthbuf_pars_vertex&gt;
  479. #include &lt;clipping_planes_pars_vertex&gt;
  480. void main() {
  481. #include &lt;uv_vertex&gt;
  482. #include &lt;uv2_vertex&gt;
  483. #include &lt;color_vertex&gt;
  484. #include &lt;skinbase_vertex&gt;
  485. #ifdef USE_ENVMAP
  486. #include &lt;beginnormal_vertex&gt;
  487. #include &lt;morphnormal_vertex&gt;
  488. #include &lt;skinnormal_vertex&gt;
  489. #include &lt;defaultnormal_vertex&gt;
  490. #endif
  491. #include &lt;begin_vertex&gt;
  492. #include &lt;morphtarget_vertex&gt;
  493. #include &lt;skinning_vertex&gt;
  494. #include &lt;project_vertex&gt;
  495. #include &lt;logdepthbuf_vertex&gt;
  496. #include &lt;worldpos_vertex&gt;
  497. #include &lt;clipping_planes_vertex&gt;
  498. #include &lt;envmap_vertex&gt;
  499. #include &lt;fog_vertex&gt;
  500. }
  501. </pre>
  502. <p>Digging through the various chunks we want to replace
  503. the <a href="https://github.com/mrdoob/three.js/blob/dev/src/renderers/shaders/ShaderChunk/morphtarget_pars_vertex.glsl.js"><code class="notranslate" translate="no">morphtarget_pars_vertex</code> chunk</a>
  504. the <a href="https://github.com/mrdoob/three.js/blob/dev/src/renderers/shaders/ShaderChunk/morphnormal_vertex.glsl.js"><code class="notranslate" translate="no">morphnormal_vertex</code> chunk</a>
  505. the <a href="https://github.com/mrdoob/three.js/blob/dev/src/renderers/shaders/ShaderChunk/morphtarget_vertex.glsl.js"><code class="notranslate" translate="no">morphtarget_vertex</code> chunk</a>
  506. the <a href="https://github.com/mrdoob/three.js/blob/dev/src/renderers/shaders/ShaderChunk/color_pars_vertex.glsl.js"><code class="notranslate" translate="no">color_pars_vertex</code> chunk</a>
  507. and the <a href="https://github.com/mrdoob/three.js/blob/dev/src/renderers/shaders/ShaderChunk/color_vertex.glsl.js"><code class="notranslate" translate="no">color_vertex</code> chunk</a></p>
  508. <p>To do that we'll make a simple array of replacements and apply them in <a href="/docs/#api/en/materials/Material.onBeforeCompile"><code class="notranslate" translate="no">Material.onBeforeCompile</code></a></p>
  509. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const material = new THREE.MeshBasicMaterial({
  510. vertexColors: true,
  511. });
  512. +const vertexShaderReplacements = [
  513. + {
  514. + from: '#include &lt;morphtarget_pars_vertex&gt;',
  515. + to: `
  516. + uniform float morphTargetInfluences[8];
  517. + `,
  518. + },
  519. + {
  520. + from: '#include &lt;morphnormal_vertex&gt;',
  521. + to: `
  522. + `,
  523. + },
  524. + {
  525. + from: '#include &lt;morphtarget_vertex&gt;',
  526. + to: `
  527. + transformed += (morphTarget0 - position) * morphTargetInfluences[0];
  528. + transformed += (morphTarget1 - position) * morphTargetInfluences[1];
  529. + transformed += (morphTarget2 - position) * morphTargetInfluences[2];
  530. + transformed += (morphTarget3 - position) * morphTargetInfluences[3];
  531. + `,
  532. + },
  533. + {
  534. + from: '#include &lt;color_pars_vertex&gt;',
  535. + to: `
  536. + varying vec3 vColor;
  537. + attribute vec3 morphColor0;
  538. + attribute vec3 morphColor1;
  539. + attribute vec3 morphColor2;
  540. + attribute vec3 morphColor3;
  541. + `,
  542. + },
  543. + {
  544. + from: '#include &lt;color_vertex&gt;',
  545. + to: `
  546. + vColor.xyz = morphColor0 * morphTargetInfluences[0] +
  547. + morphColor1 * morphTargetInfluences[1] +
  548. + morphColor2 * morphTargetInfluences[2] +
  549. + morphColor3 * morphTargetInfluences[3];
  550. + `,
  551. + },
  552. +];
  553. +material.onBeforeCompile = (shader) =&gt; {
  554. + vertexShaderReplacements.forEach((rep) =&gt; {
  555. + shader.vertexShader = shader.vertexShader.replace(rep.from, rep.to);
  556. + });
  557. +};
  558. </pre>
  559. <p>Three.js also sorts morphtargets and applies only the highest influences. This
  560. lets it allow many more morphtargets as long as only a few are used at a time.
  561. Unfortunately three.js does not provide any way to know how many morph targets
  562. will be used nor which attributes the morph targets will be assigned to. So,
  563. we'll have to look into the code and reproduce what it does here. If that
  564. algorithm changes in three.js we'll need to refactor this code.</p>
  565. <p>First we remove all the color attributes. It doesn't matter if we did not add
  566. them before as it's safe to remove an attribute that was not previously added.
  567. Then we'll compute which targets we think three.js will use and finally assign
  568. those targets to the attributes we think three.js would assign them to.</p>
  569. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const mesh = new THREE.Mesh(baseGeometry, material);
  570. scene.add(mesh);
  571. +function updateMorphTargets() {
  572. + // remove all the color attributes
  573. + for (const {name} of colorAttributes) {
  574. + baseGeometry.deleteAttribute(name);
  575. + }
  576. +
  577. + // three.js provides no way to query this so we have to guess and hope it doesn't change.
  578. + const maxInfluences = 8;
  579. +
  580. + // three provides no way to query which morph targets it will use
  581. + // nor which attributes it will assign them to so we'll guess.
  582. + // If the algorithm in three.js changes we'll need to refactor this.
  583. + mesh.morphTargetInfluences
  584. + .map((influence, i) =&gt; [i, influence]) // map indices to influence
  585. + .sort((a, b) =&gt; Math.abs(b[1]) - Math.abs(a[1])) // sort by highest influence first
  586. + .slice(0, maxInfluences) // keep only top influences
  587. + .sort((a, b) =&gt; a[0] - b[0]) // sort by index
  588. + .filter(a =&gt; !!a[1]) // remove no influence entries
  589. + .forEach(([ndx], i) =&gt; { // assign the attributes
  590. + const name = `morphColor${i}`;
  591. + baseGeometry.setAttribute(name, colorAttributes[ndx].attribute);
  592. + });
  593. +}
  594. </pre>
  595. <p>We'll return this function from our <code class="notranslate" translate="no">loadAll</code> function. This way we don't
  596. need to leak any variables.</p>
  597. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">async function loadAll() {
  598. ...
  599. + return updateMorphTargets;
  600. }
  601. +// use a no-op update function until the data is ready
  602. +let updateMorphTargets = () =&gt; {};
  603. -loadAll();
  604. +loadAll().then(fn =&gt; {
  605. + updateMorphTargets = fn;
  606. +});
  607. </pre>
  608. <p>And finally we need to call <code class="notranslate" translate="no">updateMorphTargets</code> after we've let the values
  609. be updated by the tween manager and before rendering.</p>
  610. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">function render() {
  611. ...
  612. if (tweenManager.update()) {
  613. requestRenderIfNotRequested();
  614. }
  615. + updateMorphTargets();
  616. controls.update();
  617. renderer.render(scene, camera);
  618. }
  619. </pre>
  620. <p>And with that we should have the colors animating as well as the boxes.</p>
  621. <p></p><div translate="no" class="threejs_example_container notranslate">
  622. <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/lots-of-objects-morphtargets-w-colors.html"></iframe></div>
  623. <a class="threejs_center" href="/manual/examples/lots-of-objects-morphtargets-w-colors.html" target="_blank">click here to open in a separate window</a>
  624. </div>
  625. <p></p>
  626. <p>I hope going through this was helpful. Using morphtargets either through the
  627. services three.js provides or by writing custom shaders is a common technique to
  628. move lots of objects. As an example we could give every cube a random place in
  629. another target and morph from that to their first positions on the globe. That
  630. might be a cool way to introduce the globe.</p>
  631. <p>Next you might be interested in adding labels to a globe which is covered
  632. in <a href="align-html-elements-to-3d.html">Aligning HTML Elements to 3D</a>.</p>
  633. <p>Note: We could try to just graph percent of men or percent of women or the raw
  634. difference but based on how we are displaying the info, cubes that grow from the
  635. surface of the earth, we'd prefer most cubes to be low. If we used one of these
  636. other comparisons most cubes would be about 1/2 their maximum height which would
  637. not make a good visualization. Feel free to change the <code class="notranslate" translate="no">amountGreaterThan</code> from
  638. <a href="/docs/#api/en/math/Math.max(a - b, 0)"><code class="notranslate" translate="no">Math.max(a - b, 0)</code></a> to something like <code class="notranslate" translate="no">(a - b)</code> "raw difference" or <code class="notranslate" translate="no">a / (a +
  639. b)</code> "percent" and you'll see what I mean.</p>
  640. </div>
  641. </div>
  642. </div>
  643. <script src="/manual/resources/prettify.js"></script>
  644. <script src="/manual/resources/lesson.js"></script>
  645. </body></html>