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

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