lots-of-objects-merged-vertexcolors.html 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  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 - Merged w/vertex colors</title>
  8. <style>
  9. html, body {
  10. height: 100%;
  11. margin: 0;
  12. }
  13. #c {
  14. width: 100%;
  15. height: 100%;
  16. display: block;
  17. }
  18. </style>
  19. </head>
  20. <body>
  21. <canvas id="c"></canvas>
  22. </body>
  23. <!-- Import maps polyfill -->
  24. <!-- Remove this when import maps will be widely supported -->
  25. <script async src="https://unpkg.com/[email protected]/dist/es-module-shims.js"></script>
  26. <script type="importmap">
  27. {
  28. "imports": {
  29. "three": "../../build/three.module.js"
  30. }
  31. }
  32. </script>
  33. <script type="module">
  34. import * as THREE from 'three';
  35. import * as BufferGeometryUtils from '../../examples/jsm/utils/BufferGeometryUtils.js';
  36. import {OrbitControls} from '../../examples/jsm/controls/OrbitControls.js';
  37. function main() {
  38. const canvas = document.querySelector('#c');
  39. const renderer = new THREE.WebGLRenderer({canvas});
  40. const fov = 60;
  41. const aspect = 2; // the canvas default
  42. const near = 0.1;
  43. const far = 10;
  44. const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
  45. camera.position.z = 2.5;
  46. const controls = new OrbitControls(camera, canvas);
  47. controls.enableDamping = true;
  48. controls.enablePan = false;
  49. controls.minDistance = 1.2;
  50. controls.maxDistance = 4;
  51. controls.update();
  52. const scene = new THREE.Scene();
  53. scene.background = new THREE.Color('black');
  54. {
  55. const loader = new THREE.TextureLoader();
  56. const texture = loader.load('resources/images/world.jpg', render);
  57. const geometry = new THREE.SphereGeometry(1, 64, 32);
  58. const material = new THREE.MeshBasicMaterial({map: texture});
  59. scene.add(new THREE.Mesh(geometry, material));
  60. }
  61. async function loadFile(url) {
  62. const req = await fetch(url);
  63. return req.text();
  64. }
  65. function parseData(text) {
  66. const data = [];
  67. const settings = {data};
  68. let max;
  69. let min;
  70. // split into lines
  71. text.split('\n').forEach((line) => {
  72. // split the line by whitespace
  73. const parts = line.trim().split(/\s+/);
  74. if (parts.length === 2) {
  75. // only 2 parts, must be a key/value pair
  76. settings[parts[0]] = parseFloat(parts[1]);
  77. } else if (parts.length > 2) {
  78. // more than 2 parts, must be data
  79. const values = parts.map((v) => {
  80. const value = parseFloat(v);
  81. if (value === settings.NODATA_value) {
  82. return undefined;
  83. }
  84. max = Math.max(max === undefined ? value : max, value);
  85. min = Math.min(min === undefined ? value : min, value);
  86. return value;
  87. });
  88. data.push(values);
  89. }
  90. });
  91. return Object.assign(settings, {min, max});
  92. }
  93. function addBoxes(file) {
  94. const {min, max, data} = file;
  95. const range = max - min;
  96. // these helpers will make it easy to position the boxes
  97. // We can rotate the lon helper on its Y axis to the longitude
  98. const lonHelper = new THREE.Object3D();
  99. scene.add(lonHelper);
  100. // We rotate the latHelper on its X axis to the latitude
  101. const latHelper = new THREE.Object3D();
  102. lonHelper.add(latHelper);
  103. // The position helper moves the object to the edge of the sphere
  104. const positionHelper = new THREE.Object3D();
  105. positionHelper.position.z = 1;
  106. latHelper.add(positionHelper);
  107. // Used to move the center of the cube so it scales from the position Z axis
  108. const originHelper = new THREE.Object3D();
  109. originHelper.position.z = 0.5;
  110. positionHelper.add(originHelper);
  111. const color = new THREE.Color();
  112. const lonFudge = Math.PI * .5;
  113. const latFudge = Math.PI * -0.135;
  114. const geometries = [];
  115. data.forEach((row, latNdx) => {
  116. row.forEach((value, lonNdx) => {
  117. if (value === undefined) {
  118. return;
  119. }
  120. const amount = (value - min) / range;
  121. const boxWidth = 1;
  122. const boxHeight = 1;
  123. const boxDepth = 1;
  124. const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth);
  125. // adjust the helpers to point to the latitude and longitude
  126. lonHelper.rotation.y = THREE.MathUtils.degToRad(lonNdx + file.xllcorner) + lonFudge;
  127. latHelper.rotation.x = THREE.MathUtils.degToRad(latNdx + file.yllcorner) + latFudge;
  128. // use the world matrix of the origin helper to
  129. // position this geometry
  130. positionHelper.scale.set(0.005, 0.005, THREE.MathUtils.lerp(0.01, 0.5, amount));
  131. originHelper.updateWorldMatrix(true, false);
  132. geometry.applyMatrix4(originHelper.matrixWorld);
  133. // compute a color
  134. const hue = THREE.MathUtils.lerp(0.7, 0.3, amount);
  135. const saturation = 1;
  136. const lightness = THREE.MathUtils.lerp(0.4, 1.0, amount);
  137. color.setHSL(hue, saturation, lightness);
  138. // get the colors as an array of values from 0 to 255
  139. const rgb = color.toArray().map(v => v * 255);
  140. // make an array to store colors for each vertex
  141. const numVerts = geometry.getAttribute('position').count;
  142. const itemSize = 3; // r, g, b
  143. const colors = new Uint8Array(itemSize * numVerts);
  144. // copy the color into the colors array for each vertex
  145. colors.forEach((v, ndx) => {
  146. colors[ndx] = rgb[ndx % 3];
  147. });
  148. const normalized = true;
  149. const colorAttrib = new THREE.BufferAttribute(colors, itemSize, normalized);
  150. geometry.setAttribute('color', colorAttrib);
  151. geometries.push(geometry);
  152. });
  153. });
  154. const mergedGeometry = BufferGeometryUtils.mergeBufferGeometries(
  155. geometries, false);
  156. const material = new THREE.MeshBasicMaterial({
  157. vertexColors: true,
  158. });
  159. const mesh = new THREE.Mesh(mergedGeometry, material);
  160. scene.add(mesh);
  161. }
  162. loadFile('resources/data/gpw/gpw_v4_basic_demographic_characteristics_rev10_a000_014mt_2010_cntm_1_deg.asc')
  163. .then(parseData)
  164. .then(addBoxes)
  165. .then(render);
  166. function resizeRendererToDisplaySize(renderer) {
  167. const canvas = renderer.domElement;
  168. const width = canvas.clientWidth;
  169. const height = canvas.clientHeight;
  170. const needResize = canvas.width !== width || canvas.height !== height;
  171. if (needResize) {
  172. renderer.setSize(width, height, false);
  173. }
  174. return needResize;
  175. }
  176. let renderRequested = false;
  177. function render() {
  178. renderRequested = undefined;
  179. if (resizeRendererToDisplaySize(renderer)) {
  180. const canvas = renderer.domElement;
  181. camera.aspect = canvas.clientWidth / canvas.clientHeight;
  182. camera.updateProjectionMatrix();
  183. }
  184. controls.update();
  185. renderer.render(scene, camera);
  186. }
  187. render();
  188. function requestRenderIfNotRequested() {
  189. if (!renderRequested) {
  190. renderRequested = true;
  191. requestAnimationFrame(render);
  192. }
  193. }
  194. controls.addEventListener('change', requestRenderIfNotRequested);
  195. window.addEventListener('resize', requestRenderIfNotRequested);
  196. }
  197. main();
  198. </script>
  199. </html>