threejs-lots-of-objects-merged-vertexcolors.html 6.9 KB

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