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

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