Display an elevation COG and discard no-data values.

Options
100% © U.S. Geological Survey

The NoDataOptions of the Layer class can be used to replace no-data values with interpolated neighbouring pixels.

index.js
import colormap from "colormap";

import { Color, DoubleSide } from "three";
import { MapControls } from "three/examples/jsm/controls/MapControls.js";

import Extent from "@giro3d/giro3d/core/geographic/Extent.js";
import GeoTIFFSource from "@giro3d/giro3d/sources/GeoTIFFSource.js";
import Instance from "@giro3d/giro3d/core/Instance.js";
import ElevationLayer from "@giro3d/giro3d/core/layer/ElevationLayer";
import ColorLayer from "@giro3d/giro3d/core/layer/ColorLayer.js";
import MaskLayer from "@giro3d/giro3d/core/layer/MaskLayer.js";
import Map from "@giro3d/giro3d/entities/Map.js";
import Inspector from "@giro3d/giro3d/gui/Inspector.js";
import ColorMap, { ColorMapMode } from "@giro3d/giro3d/core/layer/ColorMap.js";

function bindNumericalDropDown(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(parseInt(element.value));
  };

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

  return [callback, parseInt(element.value), element];
}

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 bindSlider(id, onChange) {
  const element = document.getElementById(id);
  if (!(element instanceof HTMLInputElement)) {
    throw new Error(
      "invalid binding element: expected HTMLInputElement, got: " +
        element.constructor.name,
    );
  }

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

  const setValue = (v) => {
    element.valueAsNumber = v;
    onChange(element.valueAsNumber);
  };

  const initialValue = element.valueAsNumber;

  return [setValue, initialValue, element];
}

Instance.registerCRS(
  "EPSG:26910",
  "+proj=utm +zone=10 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs +type=crs",
);

const extent = new Extent("EPSG:26910", 532622, 569790, 5114416, 5137240);

const center = extent.centerAsVector3();

const instance = new Instance({
  target: "view",
  crs: extent.crs,
  backgroundColor: null,
});

instance.view.camera.position.set(center.x, center.y - 1, 50000);

const controls = new MapControls(instance.view.camera, instance.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.2;
controls.target.set(center.x, center.y, center.z);
instance.view.setControls(controls);

// Use an elevation COG with nodata values
const source = new GeoTIFFSource({
  // https://pubs.er.usgs.gov/publication/ds904
  url: "https://3d.oslandia.com/dem/msh2009dem.tif",
  crs: extent.crs,
});

const values = colormap({ colormap: "viridis", nshades: 256 });
const colors = values.map((v) => new Color(v));

const min = 227;
const max = 2538;

const colorMap = new ColorMap(colors, min, max, ColorMapMode.Elevation);

const noDataOptions = {
  alpha: 0,
  maxSearchDistance: 10000,
  replaceNoData: true,
};

const map = new Map({
  extent,
  side: DoubleSide,
  backgroundOpacity: 0,
  hillshading: true,
  discardNoData: true,
});

instance.add(map);

let elevationLayer;
let maskLayer;
let colorLayer;

let activeLayer = 0;

function updateActiveLayer() {
  elevationLayer.visible = false;
  maskLayer.visible = false;
  colorLayer.visible = false;

  switch (activeLayer) {
    case 0:
      elevationLayer.visible = true;
      map.backgroundOpacity = 0;
      map.discardNoData = true;
      break;
    case 1:
      maskLayer.visible = true;
      map.backgroundOpacity = 1;
      map.discardNoData = false;
      break;
    case 2:
    default:
      colorLayer.visible = true;
      map.backgroundOpacity = 0;
      map.discardNoData = false;
      break;
  }
}

function buildLayers() {
  map.removeLayer(elevationLayer);
  map.removeLayer(maskLayer);
  map.removeLayer(colorLayer);

  maskLayer = new MaskLayer({
    name: "mask",
    extent,
    source,
    noDataOptions,
    preloadImages: false,
  });

  elevationLayer = new ElevationLayer({
    name: "elevation",
    extent,
    source,
    noDataOptions,
    colorMap,
    preloadImages: false,
    minmax: { min, max },
  });

  colorLayer = new ColorLayer({
    name: "color",
    extent,
    source,
    noDataOptions,
    colorMap,
    preloadImages: false,
  });

  map.addLayer(elevationLayer);
  map.addLayer(maskLayer);
  map.addLayer(colorLayer);

  updateActiveLayer();

  instance.notifyChange(map);
}

const [, , alphaReplacementInput] = bindNumericalDropDown(
  "alphaReplacement",
  (value) => {
    noDataOptions.alpha = value;
    instance.notifyChange(map);
  },
);

const [, , radiusSlider] = bindSlider("maxDistanceSlider", (v) => {
  noDataOptions.maxSearchDistance = v;
});

bindToggle("enableFillNoData", (state) => {
  noDataOptions.replaceNoData = state;
  if (!state) {
    radiusSlider.setAttribute("disabled", "");
    alphaReplacementInput.setAttribute("disabled", "");
  } else {
    radiusSlider.removeAttribute("disabled");
    alphaReplacementInput.removeAttribute("disabled");
  }
});

bindNumericalDropDown("noDataLayerSource", (v) => {
  activeLayer = v;
});

buildLayers();

document.getElementById("applyChanges").onclick = function onclick() {
  buildLayers();
};

Inspector.attach("inspector", instance);
index.html
<!doctype html>
<html lang="en">
  <head>
    <title>No-data elimination</title>
    <meta charset="UTF-8" />
    <meta name="name" content="cog_nodata" />
    <meta
      name="description"
      content="Display an elevation COG and discard no-data values."
    />
    <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/css/example.css"
    />

    <style>
      #view canvas {
        background-image: linear-gradient(45deg, #aaaaaa 25%, transparent 25%),
          linear-gradient(-45deg, #aaaaaa 25%, transparent 25%),
          linear-gradient(45deg, transparent 75%, #aaaaaa 75%),
          linear-gradient(-45deg, transparent 75%, #aaaaaa 75%);
        background-size: 20px 20px;
        background-position:
          0 0,
          0 10px,
          10px -10px,
          -10px 0px;
      }
    </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">
      <div class="card">
        <div class="card-header">Options</div>

        <div class="card-body" id="options">
          <div class="mb-3">
            <label for="noDataLayerSource" class="form-label">Layer type</label>
            <select
              id="noDataLayerSource"
              class="form-select"
              autocomplete="off"
            >
              <option value="0">Elevation layer</option>
              <option value="1">Mask layer</option>
              <option value="2">Color layer</option>
            </select>
          </div>

          <div class="mb-3">
            <div class="form-check form-switch">
              <input
                class="form-check-input"
                type="checkbox"
                checked="true"
                role="switch"
                id="enableFillNoData"
                autocomplete="off"
              />
              <label class="form-check-label" for="enableFillNoData"
                >Enable fill no-data</label
              >
            </div>
          </div>

          <div class="mb-3">
            <label for="alphaReplacement" class="form-label"
              >Replace no-data pixels with</label
            >
            <select
              id="alphaReplacement"
              class="form-select"
              autocomplete="off"
            >
              <option value="1">Opaque alpha</option>
              <option value="0" selected>Transparent alpha</option>
            </select>
          </div>

          <div class="mb-3">
            <label for="maxDistanceSlider" class="form-label"
              >Max distance (meters)</label
            >
            <div class="input-group">
              <input
                type="range"
                min="0"
                max="10000"
                value="10000"
                step="100"
                class="form-range"
                id="maxDistanceSlider"
                autocomplete="off"
              />
            </div>
          </div>

          <div class="mb-3">
            <button type="button" class="btn btn-primary" id="applyChanges">
              Apply changes
            </button>
          </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": "cog_nodata",
    "dependencies": {
        "colormap": "^2.3.2",
        "@giro3d/giro3d": "git+https://gitlab.com/giro3d/giro3d.git"
    },
    "devDependencies": {
        "vite": "^3.2.3"
    },
    "scripts": {
        "start": "vite",
        "build": "vite build"
    }
}