lots-of-objects-multiple-data-sets.html 10 KB

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