Visualize point cloud intensity with a colormap.

Giro3D version
THREE.js version
OpenLayers version
CRS
Memory usage (CPU)
Memory usage (GPU)
Frames
Clear color
Clear alpha
Status
Local clipping enabled
Capabilities
WebGL 2
Max texture units
Max texture size
Precision
Max fragment shader uniforms
Logarithmic depth buffer
Max shader attributes
Check shader errors
EXT_clip_control
EXT_color_buffer_float
EXT_color_buffer_half_float
EXT_conservative_depth
EXT_depth_clamp
EXT_float_blend
EXT_polygon_offset_clamp
EXT_texture_compression_bptc
EXT_texture_compression_rgtc
EXT_texture_filter_anisotropic
EXT_texture_mirror_clamp_to_edge
EXT_texture_norm16
NV_shader_noperspective_interpolation
OES_draw_buffers_indexed
OES_sample_variables
OES_shader_multisample_interpolation
OES_texture_float_linear
OVR_multiview2
WEBGL_clip_cull_distance
WEBGL_compressed_texture_astc
WEBGL_compressed_texture_etc
WEBGL_compressed_texture_etc1
WEBGL_compressed_texture_s3tc
WEBGL_compressed_texture_s3tc_srgb
WEBGL_debug_renderer_info
WEBGL_debug_shaders
WEBGL_lose_context
WEBGL_multi_draw
WEBGL_polygon_mode
WEBGL_stencil_texturing
MSAA
EDL
EDL Radius
EDL Strength
Inpainting
Inpainting steps
Inpainting depth contrib.
Point cloud occlusion
Type
FOV
Automatic plane computation
Far plane
Near plane
Max far plane
Min near plane
Width (pixels)
Height (pixels)
x
y
z
color
Enable cache
Default TTL (seconds)
Capacity (MB)
Capacity (entries)
Entries
Memory usage (approx)
Pending requests
Memory tracker
Identifier
Memory usage (CPU)
Memory usage (GPU)
Status
Render order
Enable
Plane normal X
Plane normal Y
Plane normal Z
Distance
Helper size
Negate plane
Visible
Freeze updates
Opacity
Show volumes
Cast shadow
Receive shadow
Error target
Point size
Brightness
Contrast
Saturation
Enabled
Mode
Elevation
Lower bound
Upper bound
Layers
Show helpers
Show hidden objects
Name filter
Hierarchy
Properties
isObject3D
uuid
name
type
matrixAutoUpdate
matrixWorldAutoUpdate
matrixWorldNeedsUpdate
visible
castShadow
receiveShadow
frustumCulled
renderOrder
x
y
z
x
y
z
Parameters
100% © IGN
index.js
import * as FunctionCurveEditor from "function-curve-editor";

import { Vector3 } from "three";
import { MapControls } from "three/examples/jsm/controls/MapControls.js";
import { CSS2DObject } from "three/examples/jsm/renderers/CSS2DRenderer.js";

import Instance from "@giro3d/giro3d/core/Instance.js";
import ColorMap from "@giro3d/giro3d/core/ColorMap.js";
import Tiles3D from "@giro3d/giro3d/entities/Tiles3D.js";
import Inspector from "@giro3d/giro3d/gui/Inspector.js";
import { MODE } from "@giro3d/giro3d/renderer/PointCloudMaterial.js";

function bindButton(id, onClick) {
  const element = document.getElementById(id);
  if (!(element instanceof HTMLButtonElement)) {
    throw new Error(
      "invalid binding element: expected HTMLButtonElement, got: " +
        element.constructor.name,
    );
  }

  element.onclick = () => {
    onClick(element);
  };

  return element;
}

function bindColorMapBounds(callback) {
  const min = document.getElementById("min");
  if (!(min instanceof HTMLInputElement)) {
    throw new Error(
      "invalid binding element: expected HTMLInputElement, got: " +
        min.constructor.name,
    );
  }

  const max = document.getElementById("max");
  if (!(max instanceof HTMLInputElement)) {
    throw new Error(
      "invalid binding element: expected HTMLInputElement, got: " +
        max.constructor.name,
    );
  }

  const lower = min;
  const upper = max;

  callback(lower.valueAsNumber, upper.valueAsNumber);

  function updateLabels() {
    document.getElementById("minLabel").innerText =
      `Lower bound: ${Math.round(lower.valueAsNumber)}m`;
    document.getElementById("maxLabel").innerText =
      `Upper bound: ${Math.round(upper.valueAsNumber)}m`;
  }

  lower.oninput = function oninput() {
    const rawValue = lower.valueAsNumber;
    const clampedValue = MathUtils.clamp(
      rawValue,
      Number.parseFloat(lower.min),
      upper.valueAsNumber - 1,
    );
    lower.valueAsNumber = clampedValue;
    callback(lower.valueAsNumber, upper.valueAsNumber);
    updateLabels();
  };

  upper.oninput = function oninput() {
    const rawValue = upper.valueAsNumber;
    const clampedValue = MathUtils.clamp(
      rawValue,
      lower.valueAsNumber + 1,
      Number.parseFloat(upper.max),
    );
    upper.valueAsNumber = clampedValue;
    callback(lower.valueAsNumber, upper.valueAsNumber);
    updateLabels();
  };

  const externalInput = (min, max) => {
    lower.min = min;
    lower.max = max;
    upper.min = min;
    upper.max = max;
    lower.valueAsNumber = min;
    upper.valueAsNumber = max;
    callback(lower.valueAsNumber, upper.valueAsNumber);
    updateLabels();
  };

  return externalInput;
}

function bindDropDown(id, onChange) {
  const element = document.getElementById(id);
  if (!(element instanceof HTMLSelectElement)) {
    throw new Error(
      "invalid binding element: expected HTMLSelectElement, got: " +
        element.constructor.name,
    );
  }

  element.onchange = () => {
    onChange(element.value);
  };

  const callback = (v) => {
    element.value = v;
    onChange(element.value);
  };

  const setOptions = (options) => {
    const items = options.map(
      (opt) =>
        `<option value=${opt.id} ${opt.selected ? "selected" : ""}>${opt.name}</option>`,
    );
    element.innerHTML = items.join("\n");
  };

  return [callback, element.value, element, setOptions];
}

function bindToggle(id, onChange) {
  const element = document.getElementById(id);
  if (!(element instanceof HTMLInputElement)) {
    throw new Error(
      "invalid binding element: expected HTMLButtonElement, got: " +
        element.constructor.name,
    );
  }

  element.oninput = function oninput() {
    onChange(element.checked);
  };

  const callback = (v) => {
    element.checked = v;
    onChange(element.checked);
  };

  return [callback, element.checked, element];
}

function makeColorRamp(
  preset,
  discrete = false,
  invert = false,
  mirror = false,
) {
  let nshades = discrete ? 10 : 256;

  const values = colormap({ colormap: preset, nshades });

  const colors = values.map((v) => new Color(v));

  if (invert) {
    colors.reverse();
  }

  if (mirror) {
    const mirrored = [...colors, ...colors.reverse()];
    return mirrored;
  }

  return colors;
}

Instance.registerCRS(
  "EPSG:3946",
  "+proj=lcc +lat_1=45.25 +lat_2=46.75 +lat_0=46 +lon_0=3 +x_0=1700000 " +
    "+y_0=5200000 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs",
);

const instance = new Instance({
  target: "view",
  crs: "EPSG:3946",
  backgroundColor: null, // To make canvas transparent
});

// Enable point cloud post processing effects
instance.renderingOptions.enableEDL = true;
// But not inpainting and occlusion because it would hinder the opacity filtering
instance.renderingOptions.enableInpainting = false;
instance.renderingOptions.enablePointCloudOcclusion = false;

let parameters = {
  ramp: "greys",
  discrete: false,
  invert: false,
  colors: makeColorRamp("greys", false, false),
  opacity: new Array(256).fill(1),
  min: 0,
  max: 30,
};

const url =
  "https://3d.oslandia.com/giro3d/3d-tiles/lidarhd_intensity/tileset.json";

// Create the 3D tiles entity
const pointcloud = new Tiles3D({
  url,
  pointCloudMode: MODE.INTENSITY,
  colorMap: new ColorMap({
    colors: parameters.colors,
    min: parameters.min,
    max: parameters.max,
    opacities: parameters.opacity,
  }),
});

function placeCamera(position, lookAt) {
  instance.view.camera.position.set(position.x, position.y, position.z);
  instance.view.camera.lookAt(lookAt);
  // create controls
  const controls = new MapControls(instance.view.camera, instance.domElement);
  controls.target.copy(lookAt);
  controls.enableDamping = true;
  controls.dampingFactor = 0.25;

  instance.view.setControls(controls);

  instance.notifyChange(instance.view.camera);
}

const tmpVec3 = new Vector3();

// add pointcloud to scene
function initializeCamera() {
  const bbox = pointcloud.getBoundingBox();

  instance.view.camera.far = 2.0 * bbox.getSize(tmpVec3).length();

  const lookAt = bbox.getCenter(tmpVec3);
  lookAt.z = bbox.min.z;

  // const axes = new AxesHelper(1000);

  // instance.add(axes);
  // axes.position.set(lookAt.x, lookAt.y, lookAt.z + 50);
  // axes.updateMatrixWorld(true);

  placeCamera(new Vector3(221965, 6873398, 1951), lookAt);
}

instance.add(pointcloud).then(initializeCamera);

Inspector.attach("inspector", instance);

function updatePreview(colors) {
  const canvas = document.getElementById("gradient");
  const ctx = canvas.getContext("2d");

  canvas.width = colors.length;
  canvas.height = 32;

  for (let i = 0; i < colors.length; i++) {
    const color = colors[i];
    ctx.fillStyle = `#${color.getHexString()}`;
    ctx.fillRect(i, 0, 1, canvas.height);
  }
}

updatePreview(parameters.colors);

function updateColorRamp() {
  parameters.colors = makeColorRamp(
    parameters.ramp,
    parameters.discrete,
    parameters.invert,
  );

  pointcloud.colorMap.colors = parameters.colors;
  pointcloud.colorMap.min = parameters.min;
  pointcloud.colorMap.max = parameters.max;
  pointcloud.colorMap.mode = parameters.mode;

  updateTransparency();

  updatePreview(parameters.colors);

  instance.notifyChange(pointcloud);
}

const [setDiscrete] = bindToggle("discrete", (v) => {
  parameters.discrete = v;
  updateColorRamp();
});
const [setInvert] = bindToggle("invert", (v) => {
  parameters.invert = v;
  updateColorRamp();
});
const [setRamp] = bindDropDown("ramp", (v) => {
  parameters.ramp = v;
  updateColorRamp();
  instance.notifyChange(pointcloud);
});
const updateBounds = bindColorMapBounds((min, max) => {
  pointcloud.colorMap.min = min;
  pointcloud.colorMap.max = max;
  instance.notifyChange(pointcloud);
});

const canvas = document.getElementById("curve");

const widget = new FunctionCurveEditor.Widget(canvas);

function updateTransparency() {
  const length = parameters.colors.length;
  const f = widget.getFunction();
  const opacities = new Array(length);
  for (let i = 0; i < length; i++) {
    const t = i / length;
    opacities[i] = f(t);
  }
  parameters.opacity = opacities;
  pointcloud.colorMap.opacity = opacities;
}

function setupCurveEditor() {
  // Curve editor
  const initialKnots = [
    { x: 0, y: 1 },
    { x: 1, y: 1 },
  ];

  widget.setEditorState({
    knots: initialKnots,
    xMin: -0.2,
    xMax: 1.2,
    yMin: -0.2,
    yMax: 1.2,
    interpolationMethod: "linear",
    extendedDomain: true,
    relevantXMin: 0,
    relevantXMax: 1,
    gridEnabled: true,
  });

  widget.addEventListener("change", () => {
    updateColorRamp();
  });
}

setupCurveEditor();

function resetToDefaults() {
  setupCurveEditor();

  setRamp("greys");
  setDiscrete(false);
  setInvert(false);
  updateBounds(0, 30);

  parameters = {
    ramp: "greys",
    discrete: false,
    invert: false,
    colors: makeColorRamp("greys", false, false),
    opacity: new Array(256).fill(1),
    min: 0,
    max: 30,
  };

  pointcloud.colorMap.active = true;

  updateColorRamp();

  instance.notifyChange(pointcloud);
}

bindButton("reset", resetToDefaults);

const labelElement = document.createElement("div");
labelElement.classList.value = "badge rounded-pill text-bg-light";
labelElement.style.marginTop = "2rem";

const intensityValue = document.createElement("span");
intensityValue.style.marginLeft = "0.5rem";

const intensityColor = document.createElement("span");
intensityColor.classList.value = "badge rounded-pill";
intensityColor.style.color = "white";
intensityColor.style.background = "red";
intensityColor.style.width = "1rem";
intensityColor.innerText = " ";

labelElement.appendChild(intensityColor);
labelElement.appendChild(intensityValue);

const label = new CSS2DObject(labelElement);

instance.add(label);

// Let's query the intensity of the picked point and display it in the label.
function updateLabel(mouseEvent) {
  const results = instance.pickObjectsAt(mouseEvent, { radius: 6 });

  // Reset label visibility
  label.visible = false;

  if (results && results.length > 0) {
    for (const result of results) {
      const { object, point, index } = result;

      if (object.geometry) {
        const intensity = object.geometry
          .getAttribute("intensity")
          ?.getX(index);

        if (intensity) {
          const color = pointcloud.colorMap.sample(intensity);
          const opacity = pointcloud.colorMap.sampleOpacity(intensity);

          if (opacity > 0.5) {
            const hex = color.getHexString();
            intensityColor.style.background = `#${hex}`;

            intensityValue.innerText = `${intensity.toFixed(2)}`;

            label.visible = true;
            label.position.copy(point);
            label.updateMatrixWorld(true);

            break;
          }
        }
      }
    }
  }

  instance.notifyChange();
}

instance.domElement.addEventListener("mousemove", updateLabel);

// For some reason we have to wait a bit in order to the curve editor to display properly on Firefox.
setTimeout(resetToDefaults, 100);
index.html
<!doctype html>
<html lang="en">
  <head>
    <title>Point cloud intensity</title>
    <meta charset="UTF-8" />
    <meta name="name" content="point_cloud_intensity" />
    <meta
      name="description"
      content="Visualize point cloud intensity with a colormap."
    />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <link rel="icon" href="https://giro3d.org/images/favicon.svg" />
    <link
      href="https://giro3d.org/assets/bootstrap-custom.css"
      rel="stylesheet"
    />
    <script src="https://giro3d.org/assets/bootstrap.bundle.min.js"></script>
    <link
      rel="stylesheet"
      type="text/css"
      href="https://giro3d.org/next/examples/css/example.css"
    />

    <style>
      #view canvas {
        background: rgb(132, 170, 182);
        background: radial-gradient(
          circle,
          rgba(132, 170, 182, 1) 0%,
          rgba(37, 44, 48, 1) 100%
        );
      }
    </style>
  </head>

  <body>
    <div id="view" class="m-0 p-0 w-100 h-100"></div>
    <div
      id="inspector"
      class="position-absolute top-0 start-0 mh-100 overflow-auto"
    ></div>

    <div class="side-pane-with-status-bar" style="width: 20rem">
      <!--Parameters -->
      <div class="card">
        <div class="card-header">
          Parameters
          <button
            type="button"
            id="reset"
            class="btn btn-sm btn-primary rounded float-end"
          >
            reset
          </button>
        </div>

        <div class="card-body" id="top-options">
          <!-- Reverse color map -->
          <div class="form-check form-switch mb-1">
            <input
              class="form-check-input"
              type="checkbox"
              role="switch"
              id="invert"
              autocomplete="off"
            />
            <label class="form-check-label" for="invert"
              >Invert color map</label
            >
          </div>

          <!-- Discrete color map -->
          <div class="form-check form-switch mb-3">
            <input
              class="form-check-input"
              type="checkbox"
              role="switch"
              id="discrete"
              autocomplete="off"
            />
            <label class="form-check-label" for="discrete"
              >Discrete color map</label
            >
          </div>

          <!-- Color ramp selector -->
          <div class="input-group mb-3">
            <label class="input-group-text" for="ramp">Colors</label>
            <select class="form-select" id="ramp" autocomplete="off">
              <option value="greys" selected>Greys</option>
              <option value="viridis">Viridis</option>
              <option value="jet">Jet</option>
              <option value="blackbody">Blackbody</option>
              <option value="earth">Earth</option>
              <option value="bathymetry">Bathymetry</option>
              <option value="magma">Magma</option>
              <option value="par">Par</option>
              <option value="rdbu">RdBu</option>
            </select>
          </div>

          <!-- Gradient preview -->
          <div class="mb-3 w-100">
            <canvas
              id="gradient"
              height="32"
              class="w-100 border rounded"
              style="height: 32px; image-rendering: pixelated"
            ></canvas>
          </div>

          <!-- Opacity curve -->
          <div class="mb-3 w-100">
            <label for="curve" class="mb-2">Opacity curve</label>
            <canvas
              id="curve"
              height="128"
              class="w-100"
              style="height: 128px"
            ></canvas>
          </div>

          <!-- Bound sliders -->
          <div class="input-group border rounded p-2">
            <label for="min" id="minLabel" class="form-label"
              >Lower bound</label
            >
            <div class="input-group">
              <input
                type="range"
                min="0"
                max="30"
                value="0"
                class="form-range"
                id="min"
                autocomplete="off"
              />
            </div>

            <label for="max" id="maxLabel" class="form-label"
              >Upper bound</label
            >
            <div class="input-group">
              <input
                type="range"
                min="0"
                max="30"
                value="30"
                class="form-range"
                id="max"
                autocomplete="off"
              />
            </div>
          </div>
        </div>
      </div>
    </div>

    <script type="module" src="index.js"></script>
    <script>
      /* activate popovers */
      const popoverTriggerList = [].slice.call(
        document.querySelectorAll('[data-bs-toggle="popover"]'),
      );
      popoverTriggerList.map(
        // bootstrap is used as script in the template, disable warning about undef
        // eslint-disable-next-line no-undef
        (popoverTriggerEl) =>
          new bootstrap.Popover(popoverTriggerEl, {
            trigger: "hover",
            placement: "left",
            content: document.getElementById(
              popoverTriggerEl.getAttribute("data-bs-content"),
            ).innerHTML,
            html: true,
          }),
      );
    </script>
  </body>
</html>
package.json
{
    "name": "point_cloud_intensity",
    "dependencies": {
        "colormap": "^2.3.2",
        "function-curve-editor": "^1.0.16",
        "@giro3d/giro3d": "git+https://gitlab.com/giro3d/giro3d.git"
    },
    "devDependencies": {
        "vite": "^3.2.3"
    },
    "scripts": {
        "start": "vite",
        "build": "vite build"
    }
}