Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(source): add support for Cloud Optimized GeoTiff #1307

Closed
wants to merge 7 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
209 changes: 209 additions & 0 deletions examples/js/plugins/COGSource.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,209 @@

/**
* @classdesc
* An object defining the source of resources to get from a [COG]{@link
* https://www.cogeo.org/} file. It
* inherits from {@link Source}.
*
* @extends Source
*
* @property {boolean} isCOGSource - Used to checkout whether this source is a
* COGSource. Default is true. You should not change this, as it is used
* internally for optimisation.
* @property {boolean} isInverted - The isInverted property is to be set to the
* correct value, true or false (default being false) if the computation of the
* coordinates needs to be inverted to match the same scheme as OSM, Google Maps
* or other system. See [this link]{@link
* https://alastaira.wordpress.com/2011/07/06/converting-tms-tile-coordinates-to-googlebingosm-tile-coordinates/}
* for more information.
* @property {string} tileMatrixSet - Tile matrix set of the layer, used in the
* generation of the coordinates to build the url. Default value is 'WGS84'.
* @property {Object} zoom - Object containing the minimum and maximum values of
* the level, to zoom in the source.
* @property {number} zoom.min - The minimum level of the source. Default value
* is computed from the COG file.
* @property {number} zoom.max - The maximum level of the source. Default value
* is computed from the COG file.
*
* @example
* // Create the source
* const cogSource = new itowns.COGSource({
* url: 'http://osm.io/styles/${z}/${x}/${y}.png',
* tileMatrixSet: 'PM',
* parser: TIFFParser.parse,
* fetcher: itowns.Fetcher.arrayBuffer,
* });
*
* // Create the layer
* const colorLayer = new itowns.ColorLayer('COG', {
* source: cogSource,
* });
*
* // Add the layer
* view.addLayer(colorLayer);
*/
class COGSource extends itowns.Source {
/**
* @param {Object} source - An object that can contain all properties of a
* COGSource and {@link Source}. Only `url` is mandatory.
*
* @constructor
*/
constructor(source) {
if (!source.projection) {
throw new Error('New COGSource: projection is required');
}
super(source);

this.isCOGSource = true;

if (source.zoom) {
this.zoom = source.zoom;
}

this.isInverted = source.isInverted || false;
this.format = this.format || 'image/png';
this.url = source.url;

if (source.projection) {
this.projection = itowns.CRS.formatToTms(source.projection);
}

this.tileMatrixSetLimits = source.tileMatrixSetLimits;

// Header
// default is 16ko block read
this.whenReady = fetch(this.url, {
headers: {
'content-type': 'multipart/byteranges',
'range': 'bytes=0-16000',
},
}).then((response) => {
if (response.ok) {
return response.arrayBuffer();
}
}).then((response) => {
this.ifds = UTIF.decode(response);
console.log(this.ifds);
// Georef
this.modelTiepointTag = this.ifds[0].t33922;
this.modelPixelScaleTag = this.ifds[0].t33550;
this.geoKeyDirectoryTag = this.ifds[0].t34735;
this.geoDoubleParamsTag = this.ifds[0].t34736;
this.geoAsciiParamsTag = this.ifds[0].t34737;

if ((this.geoKeyDirectoryTag) && !(source.projection)) {
// Spec in http://geotiff.maptools.org/spec/geotiff2.4.html
var nbKeys = this.geoKeyDirectoryTag[3];
for (let i = 0; i < nbKeys; ++i) {
if (this.geoKeyDirectoryTag[(i + 1) * 4] == 3072) {
const epsg_code = this.geoKeyDirectoryTag[(i + 1) * 4 + 3];
this.projection = CRS.formatToTms(`EPSG:${epsg_code}`);
console.log(this.projection);
}
}
}

this.tileSize = this.ifds[0].t322[0];
this.width = this.ifds[0].t256[0];
this.height = this.ifds[0].t257[0];
this.zoomMax = Math.ceil(Math.log2(Math.max(this.width, this.height) / this.tileSize));
console.log('zoomMax : ', this.zoomMax);
if (!this.zoom) {

this.zoom = {
min: this.zoomMax - this.ifds.length + 1,
max: this.zoomMax,
};
console.log(this.zoom);
}
var tileMaxtrixSetLimits = {};
var level = this.zoom.max;
this.ifds.forEach((ifd) => {
// Format Image
// var bitsPerSample = ifd.t258;
// var sampleFormat = ifd.t339;
// console.log('Nombre de canaux : ', bitsPerSample.length);
const width = ifd.t256[0];
const height = ifd.t257[0];
// var tileOffsets = ifd.t324;
// var tileByteCounts = ifd.t325;
const tileWidth = ifd.t322[0];
const tileHeight = ifd.t323[0];
ifd.nbTileX = Math.ceil(width / tileWidth);
ifd.nbTileY = Math.ceil(height / tileHeight);
tileMaxtrixSetLimits[level] = {
"minTileRow": 0,
"maxTileRow": ifd.nbTileY,
"minTileCol": 0,
"maxTileCol": ifd.nbTileX,
}
if ((this.tileSize != tileHeight) || (this.tileSize != tileWidth)) {
console.warn('all tiles must have same dimensions');
}
level -= 1;
});
if (!this.tileMaxtrixSetLimits) {
this.tileMaxtrixSetLimits = tileMaxtrixSetLimits;
}
});
// if (!this.zoom) {
// if (this.tileMatrixSetLimits) {
// const arrayLimits = Object.keys(this.tileMatrixSetLimits);
// const size = arrayLimits.length;
// const maxZoom = Number(arrayLimits[size - 1]);
// const minZoom = maxZoom - size + 1;

// this.zoom = {
// min: minZoom,
// max: maxZoom,
// };
// } else {
// this.zoom = { min: 0, max: 20 };
// }
// }
}

urlFromExtent(extent) {
// Copy Ifd and add if to extent (for the parser)
const ifdNum = this.zoomMax - extent.zoom;
extent.ifd = JSON.parse(JSON.stringify(this.ifds[ifdNum]));
// get the offset/byteCount for the tile
const numTile = extent.col + extent.row * extent.ifd.nbTileX;
const offset = extent.ifd.t324[numTile];
const byteCounts = extent.ifd.t325[numTile];
// custom the networkOptions as a range request for this specific tile
this.networkOptions.headers = {
'content-type': 'multipart/byteranges',
'range': `bytes=${offset}-${offset + byteCounts}`,
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think you can ask 1 byte less :
'range': `bytes=${offset}-${offset + byteCounts-1}

};
// update the ifd copy for the TIFFParser
// width/heigth from the tile size
extent.ifd.t256[0] = extent.ifd.t322[0];
extent.ifd.t257[0] = extent.ifd.t323[0];
// offset and byteCounts
extent.ifd.t324 = [0];
extent.ifd.t325 = [byteCounts];
return this.url;
}

handlingError(err) {
console.warn(`err ${this.url}`, err);
}

extentInsideLimit(extent) {
// This layer provides data starting at level = layer.source.zoom.min
// (the zoom.max property is used when building the url to make
// sure we don't use invalid levels)
return extent.zoom >= this.zoom.min && extent.zoom <= this.zoom.max &&
(this.tileMatrixSetLimits == undefined ||
(extent.row >= this.tileMatrixSetLimits[extent.zoom].minTileRow &&
extent.row <= this.tileMatrixSetLimits[extent.zoom].maxTileRow &&
extent.col >= this.tileMatrixSetLimits[extent.zoom].minTileCol &&
extent.col <= this.tileMatrixSetLimits[extent.zoom].maxTileCol));
}
}

if (typeof module != 'undefined' && module.exports) {
module.exports = COGSource;
}
2 changes: 1 addition & 1 deletion examples/js/plugins/TIFFParser.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ var TIFFParser = (function _() {
* @memberof module:TIFFParser
*/
parse: function _(data) {
var IFD = UTIF.decode(data)[0];
var IFD = data.extent.ifd || UTIF.decode(data)[0];
UTIF.decodeImage(data, IFD);
IFD.data = UTIF.toRGBA8(IFD);

Expand Down
64 changes: 64 additions & 0 deletions examples/source_file_cog.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
<html>
<head>
<title>Cloud Optimized GeoTiff</title>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="css/example.css">
<link rel="stylesheet" type="text/css" href="css/LoadingScreen.css">

<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdnjs.cloudflare.com/ajax/libs/dat-gui/0.7.6/dat.gui.min.js"></script>
</head>
<body>
<div id="viewerDiv"></div>
<script src="js/GUI/GuiTools.js"></script>
<script src="https://cdn.jsdelivr.net/npm/utif@3.1.0/UTIF.js"></script>
<script src="../dist/itowns.js"></script>
<script src="../dist/debug.js"></script>
<script src="js/GUI/LoadingScreen.js"></script>
<script src="js/plugins/TIFFParser.js"></script>
<script src="js/plugins/COGSource.js"></script>
<script type="text/javascript">

itowns.proj4.defs('EPSG:2154', '+proj=lcc +lat_1=49 +lat_2=44 +lat_0=46.5 +lon_0=3 +x_0=700000 +y_0=6600000 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs');

// // # Simple Planar viewer

// // Define geographic extent: CRS, min/max X, min/max Y
// // Upper Left ( 884000.000, 6461000.000) ( 5d20'41.10"E, 45d13'25.46"N)
// // Lower Left ( 884000.000, 6459000.000) ( 5d20'38.38"E, 45d12'20.66"N)
// // Upper Right ( 886000.000, 6461000.000) ( 5d22'12.80"E, 45d13'23.53"N)
// // Lower Right ( 886000.000, 6459000.000) ( 5d22'10.05"E, 45d12'18.73"N)
// // Center ( 885000.000, 6460000.000) ( 5d21'25.58"E, 45d12'52.10"N)

var extent = new itowns.Extent(
'EPSG:2154',
884000, 886000,
6459000, 6461000);

// // `viewerDiv` will contain iTowns' rendering area (`<canvas>`)
var viewerDiv = document.getElementById('viewerDiv');

// // Instanciate iTowns PlanarView*
var view = new itowns.PlanarView(viewerDiv, extent, { disableSkirt: true, maxSubdivisionLevel: 10, placement: { tilt: 90 } });

setupLoadingScreen(viewerDiv, view);
new itowns.PlanarControls(view, {});

// // Add one imagery layer to the scene, read from TIFFs.
var cogSource = new COGSource({
url: '/cogeo.tif',
tileMatrixSet: 'PM',
projection: 'EPSG:2154',
parser: TIFFParser.parse,
fetcher: itowns.Fetcher.arrayBuffer,
});

var cogLayer = new itowns.ColorLayer('cog', {
source: cogSource,
});

view.addLayer(cogLayer);

</script>
</body>
</html>