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

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