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

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