Three.js - Lots of Objects - Merged

by Lazaro Contreras

HTML

<canvas id="c"></canvas>

CSS

body {
  margin: 0;
}

#c {
  width: 100vw;
  height: 100vh;
  display: block;
}

JavaScript

// Three.js - Lots of Objects - Merged
// from https://threejsfundamentals.org/threejs/threejs-lots-of-objects-merged.html

import * as THREE from 'https://threejsfundamentals.org/threejs/resources/threejs/r110/build/three.module.js';
import {BufferGeometryUtils} from 'https://threejsfundamentals.org/threejs/resources/threejs/r110/examples/jsm/utils/BufferGeometryUtils.js';
import {OrbitControls} from 'https://threejsfundamentals.org/threejs/resources/threejs/r110/examples/jsm/controls/OrbitControls.js';

function main() {
  const canvas = document.querySelector('#c');
  const renderer = new THREE.WebGLRenderer({canvas});

  const fov = 60;
  const aspect = 2;  // the canvas default
  const near = 0.1;
  const far = 10;
  const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
  camera.position.z = 2.5;

  const controls = new OrbitControls(camera, canvas);
  controls.enableDamping = true;
  controls.enablePan = false;
  controls.minDistance = 1.2;
  controls.maxDistance = 4;
  controls.update();
  
  let mesh = new THREE.Mesh();
  const scene = new THREE.Scene();
  scene.background = new THREE.Color('black');

  {
    const geometry = new THREE.SphereBufferGeometry(1, 64, 32);
    geometry.center();
    const material = new THREE.MeshBasicMaterial({color: "black", transparent: true});
    material.opacity = 0.7;
    scene.add(new THREE.Mesh(geometry, material));
  }

  async function loadFile(url) {
    const req = await fetch(url);
    return req.text();
  }

  function parseData(text) {
    const data = [];
    const settings = {data};
    let max;
    let min;
    // split into lines
    text.split('\n').forEach((line) => {
      // split the line by whitespace
      const parts = line.trim().split(/\s+/);
      if (parts.length === 2) {
        // only 2 parts, must be a key/value pair
        settings[parts[0]] = parseFloat(parts[1]);
      } else if (parts.length > 2) {
        // more than 2 parts, must be data
        const values =...