Parameters
Visualize point cloud intensity with a colormap.
import colormap from "colormap";
import * as FunctionCurveEditor from "function-curve-editor";
import { MathUtils, Vector3, Color } 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 Tiles3D from "@giro3d/giro3d/entities/Tiles3D.js";
import PointCloudMaterial, {
MODE,
} from "@giro3d/giro3d/renderer/PointCloudMaterial.js";
import Tiles3DSource from "@giro3d/giro3d/sources/Tiles3DSource.js";
import Inspector from "@giro3d/giro3d/gui/Inspector.js";
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 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 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 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;
}
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;
}
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;
// Create a custom material for our point cloud.
const material = new PointCloudMaterial({ mode: MODE.INTENSITY });
material.colorMap.min = 0;
material.colorMap.max = 30;
material.colorMap.colors = makeColorRamp("greys");
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(new Tiles3DSource(url), {
material,
});
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.root.boundingVolume.box
.clone()
.applyMatrix4(pointcloud.root.matrixWorld);
instance.view.camera.far = 2.0 * bbox.getSize(tmpVec3).length();
const lookAt = bbox.getCenter(tmpVec3);
lookAt.z = bbox.min.z;
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,
);
material.colorMap.colors = parameters.colors;
material.colorMap.min = parameters.min;
material.colorMap.max = parameters.max;
material.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) => {
material.colorMap.min = min;
material.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;
material.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,
};
material.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.isPointCloud) {
const intensity = object.getIntensity(index);
if (intensity) {
const color = material.colorMap.sample(intensity);
const opacity = material.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);
<!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>
{
"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"
}
}