repl.html 36.6 KB
Newer Older
Iván Sánchez Ortega's avatar
Iván Sánchez Ortega committed
1 2 3 4
<!DOCTYPE html>
<html lang='en'>
<meta charset="utf-8">
<head>
5
	<title>Leaflet TileLayer.GL interactive demo</title>
Iván Sánchez Ortega's avatar
Iván Sánchez Ortega committed
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59

<link rel="stylesheet" href="https://unpkg.com/leaflet@1.0.3/dist/leaflet.css"
  integrity="sha512-07I2e+7D8p6he1SIM+1twR5TIrhUQn9+I6yjqD53JQjFiMf8EtC93ty0/5vJTZGF8aAocvHYNEDJajGdNx1IsQ=="
  crossorigin=""/>
<script src="https://unpkg.com/leaflet@1.0.3/dist/leaflet-src.js"
  integrity="sha512-WXoSHqw/t26DszhdMhOXOkI7qCiv5QWXhH9R7CgvgZMHz1ImlkVQ3uNsiQKu5wwbbxtPzFXd1hK4tzno2VqhpA=="
  crossorigin=""></script>

	<link rel="stylesheet" href="https://unpkg.com/codemirror@5.25.2/lib/codemirror.css"/>
	<script src="https://unpkg.com/codemirror@5.25.2/lib/codemirror.js"></script>

	<meta name="viewport" content="width=device-width, initial-scale=1.0">

	<script src="../src/Leaflet.TileLayer.GL.js"></script>

	<link rel="stylesheet" media="screen" href="https://fontlibrary.org/face/orkney" type="text/css"/>

	<style>

	body {
		margin: 0;
		font-family: 'OrkneyRegular';
		font-weight: normal;
		font-style: normal;
	}

	#map {
		position:absolute;
		left: 50vw;
		right:0;
		top:0;
		bottom: 0;
	}

	#not-the-map {
		position:absolute;
		right: 50vw;
		left:0;
		top:0;
		bottom: 0;
	}

	#not-the-map textarea {
		width: 100%;
		resize: vertical;
	}

	.readonly-code-mirror {
		background: #C0C0C0;
	}

	#error-modal {
		z-index: 10;
		border: 2px solid red;
60 61
		background: white;
		color: black;
Iván Sánchez Ortega's avatar
Iván Sánchez Ortega committed
62
		font-family: monospace;
63 64 65 66 67 68 69 70 71
		white-space: pre-wrap;

		position: absolute;
		top: 10vh;
		bottom: 10vh;
		left: 60vw;
		right: 10vw;

		display: none;
Iván Sánchez Ortega's avatar
Iván Sánchez Ortega committed
72 73 74 75 76 77 78 79 80 81
	}

	</style>


</head>
<body>

	<div id="not-the-map">
<!-- 	<h1><a href='https://gitlab.com/IvanSanchez/Leaflet.TileLayer.GL'>Leaflet.TileLayer.GL</a> playground</h1> -->
82
		<h4>L.TileLayer.GL playground</h1>
Iván Sánchez Ortega's avatar
Iván Sánchez Ortega committed
83

84 85 86
		<p>Load one of the preset demos: <select id='demo-selector'></select></p>
		<hr>

Iván Sánchez Ortega's avatar
Iván Sánchez Ortega committed
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
		<p>This is a list of up to 8 tileservers to fetch tiles from. Syntax is the same as a <tt>L.TileLayer</tt>.</p>

		<textarea id="tileServers">http://{s}.tile.stamen.com/toner/{z}/{x}/{y}.png</textarea>

		<p>This is the fragment shader code. It runs once per pixel.</p>
<!-- 		<p><tt>L.TileLayer.GL</tt> predefines a set of <i>varyings</i> and one <i>texture uniform</i> per tile origin. You do not need to write that by yourself.</p> -->
		<textarea id="fragmentShaderHeader" readonly></textarea>
		<textarea id="fragmentShaderCode">
void main(void) {
	// Fetch the colour from the corresponding pixel in the texture (texel)
	vec4 texelColour = texture2D(uTexture0, vec2(vTextureCoords.s, vTextureCoords.t));

	// This would output the image "as is"
	// gl_FragColor = texelColour;

	// Let's mix the colours a little bit
	gl_FragColor = vec4(1.0 - texelColour.rg, texelColour.b, 1.0);
}
		</textarea>
	</div>

	<div id="map"></div>
109
	<pre id="error-modal"></pre>
Iván Sánchez Ortega's avatar
Iván Sánchez Ortega committed
110 111 112

	<script type="text/javascript">

113 114

		// Set up the code editors
Iván Sánchez Ortega's avatar
Iván Sánchez Ortega committed
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
		var tileServersMirror = CodeMirror.fromTextArea(document.getElementById('tileServers'), {
			lineNumbers: true,
			lineWrapping: true,
			firstLineNumber: 0
		});

		tileServersMirror.setSize('100%', '8rem');

		var fragmentHeaderMirror = CodeMirror.fromTextArea(document.getElementById('fragmentShaderHeader'), {
// 			mode: "glsl",
			mode: "javascript",
			lineNumbers: true,
			lineWrapping: true,
			firstLineNumber: 1,
			readOnly: true
		});

		fragmentHeaderMirror.getWrapperElement().className += ' readonly-code-mirror';
133
		fragmentHeaderMirror.setSize('100%', '4rem');
Iván Sánchez Ortega's avatar
Iván Sánchez Ortega committed
134 135 136 137 138 139 140 141 142

		var fragmentCodeMirror = CodeMirror.fromTextArea(document.getElementById('fragmentShaderCode'), {
// 			mode: "glsl",
			mode: "javascript",
			lineNumbers: true,
			lineWrapping: true,
			firstLineNumber: 5
		});

143
		// Preset demos
144
		var mapboxAccessToken = 'pk.eyJ1IjoienN0YWRsZXIiLCJhIjoiY2lvbDc5Zzl6MDAwc3Z2bTZ6NDNybDM3dSJ9.vxR1WVn26mEtpEk9MzdiUA';
145 146
		var sentinelhubKey = '0f03c55a-804e-33bd-8589-da814f6575ae';
		
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
		var demos = {

			"Empty": {
				tiles: [],
				shader: ""
			},

			"Basic colour channel inversion": {
				tiles: ['http://{s}.tile.stamen.com/toner/{z}/{x}/{y}.png'],
				shader:
					"void main(void) {                                                                    \n" +
					"	vec4 texelColour = texture2D(uTexture0, vec2(vTextureCoords.s, vTextureCoords.t));\n" +
					"                                                                                     \n" +
					"	// This would output the image \"as is\"                                          \n" +
					"	// gl_FragColor = texelColour;                                                    \n" +
					"                                                                                     \n" +
					"	// Let's mix the colours a little bit                                             \n" +
					"	gl_FragColor = vec4(1.0 - texelColour.rg, texelColour.b, 1.0);                    \n" +
					"}                                                                                    \n"
			},

			"Conditional colouring": {
				tiles: ['http://{s}.tile.stamen.com/toner/{z}/{x}/{y}.png'],
				shader:
					"void main(void) {                                                                            \n" +
					"	vec4 texelColour = texture2D(uTexture0, vec2(vTextureCoords.s, vTextureCoords.t));        \n" +
					"	vec4 stop;                                                                                \n" +
					"                                                                                             \n" +
					"	// Color stops. The alpha value represents the latitude minimum for that RGB colour stop. \n" +
					"	// Latitudes are expressed in EPSG:3875 units, not in degrees of latitude.                \n" +
					"	vec4 stops[5];                                                                            \n" +
					"	stops[0] = vec4(0.444, 0.691, 1.0,   -20037508);	// Blue-ish north of -90              \n" +
					"	stops[1] = vec4(0.333, 0.666, 0.333, -10015051);	// Green-ish north of -66.5           \n" +
					"	stops[2] = vec4(0.9, 0.75, 0.35,      -2571663);	// Orange-ish north of -22.5          \n" +
					"	stops[3] = vec4(0.333, 0.666, 0.333,   2571663);	// Green-ish north of 22.5            \n" +
					"	stops[4] = vec4(0.444, 0.691, 1.0,    10015051);	// Blue-ish north of 66.5             \n" +
					"                                                                                             \n" +
					"	// Find which colour stop we want to use                                                  \n" +
					"	for (int i=0; i < 5; i++) {                                                               \n" +
					"		if (vCRSCoords.y > stops[i].a) {                                                      \n" +
					"			stop = stops[i];                                                                  \n" +
					"		}                                                                                     \n" +
					"	}                                                                                         \n" +
					"                                                                                             \n" +
					"	// Multiply the black in the texel by the stop colour                                     \n" +
					"	gl_FragColor = vec4(                                                                      \n" +
					"		vec3(1.0) - (texelColour.rgb) * (vec3(1.0) - stop.rgb)                                \n" +
					"	, 1.0);                                                                                   \n" +
					"}                                                                                            \n"
			},

198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
			"Hue rotation": {
				tiles: ['http://{s}.tile.stamen.com/terrain/{z}/{x}/{y}.png'],
				shader:
					"vec3 rgb2hsv(vec3 c) {                                                                  \n" +
					"    vec4 K = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0);                                    \n" +
					"    vec4 p = mix(vec4(c.bg, K.wz), vec4(c.gb, K.xy), step(c.b, c.g));                   \n" +
					"    vec4 q = mix(vec4(p.xyw, c.r), vec4(c.r, p.yzx), step(p.x, c.r));                   \n" +
					"                                                                                        \n" +
					"    float d = q.x - min(q.w, q.y);                                                      \n" +
					"    float e = 1.0e-10;                                                                  \n" +
					"    return vec3(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x);            \n" +
					"}                                                                                       \n" +
					"                                                                                        \n" +
					"vec3 hsv2rgb(vec3 c) {                                                                  \n" +
					"    vec4 K = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0);                                      \n" +
					"    vec3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www);                                   \n" +
					"    return c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y);                           \n" +
					"}                                                                                       \n" +
					"                                                                                        \n" +
					"void main(void) {                                                                       \n" +
					"    vec4 texelColour = texture2D(uTexture0, vec2(vTextureCoords.s, vTextureCoords.t));  \n" +
219
					"    vec3 hsv = rgb2hsv(texelColour.rgb);                                                \n" +
220 221 222 223 224 225 226 227
					"                                                                                        \n" +
					"    hsv.x += 0.3;	// Change this number to vary the amount of hue rotation             \n" +
					"    // hsv.y *= 0.3;   // Try changing the colour saturation!                           \n" +
					"                                                                                        \n" +
					"    gl_FragColor = vec4(hsv2rgb(hsv), texelColour.a);                                   \n" +
					"}                                                                                       \n"
			},

228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
			"Animated hue rotation": {
				tiles: ['http://{s}.tile.stamen.com/terrain/{z}/{x}/{y}.png'],
				shader:
					"vec3 rgb2hsv(vec3 c) {                                                                  \n" +
					"    vec4 K = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0);                                    \n" +
					"    vec4 p = mix(vec4(c.bg, K.wz), vec4(c.gb, K.xy), step(c.b, c.g));                   \n" +
					"    vec4 q = mix(vec4(p.xyw, c.r), vec4(c.r, p.yzx), step(p.x, c.r));                   \n" +
					"                                                                                        \n" +
					"    float d = q.x - min(q.w, q.y);                                                      \n" +
					"    float e = 1.0e-10;                                                                  \n" +
					"    return vec3(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x);            \n" +
					"}                                                                                       \n" +
					"                                                                                        \n" +
					"vec3 hsv2rgb(vec3 c) {                                                                  \n" +
					"    vec4 K = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0);                                      \n" +
					"    vec3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www);                                   \n" +
					"    return c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y);                           \n" +
					"}                                                                                       \n" +
					"                                                                                        \n" +
					"void main(void) {                                                                       \n" +
					"    vec4 texelColour = texture2D(uTexture0, vec2(vTextureCoords.s, vTextureCoords.t));  \n" +
					"    vec3 hsv = rgb2hsv(texelColour.rgb);                                                \n" +
					"                                                                                        \n" +
					"    // Hue will rotate fully once every 2 seconds.                                                                                    \n" +
					"    hsv.x += fract(0.3 + (uNow / 2000.0));	                                             \n" +
					"                                                                                        \n" +
					"    gl_FragColor = vec4(hsv2rgb(hsv), texelColour.a);                                   \n" +
					"}                                                                                       \n"
			},

258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
			"Flood & height": {
				tiles: [
					'http://{s}.basemaps.cartocdn.com/light_nolabels/{z}/{x}/{y}.png',
					'http://{s}.basemaps.cartocdn.com/light_only_labels/{z}/{x}/{y}.png',
					'https://{s}.tiles.mapbox.com/v4/mapbox.terrain-rgb/{z}/{x}/{y}.pngraw?access_token=' + mapboxAccessToken
					],
				shader:
					"void main(void) {                                                                          \n" +
					"	// Fetch color from texture 2, which is the terrain-rgb tile                            \n" +
					"	highp vec4 texelColour = texture2D(uTexture2, vec2(vTextureCoords.s, vTextureCoords.t));\n" +
					"                                                                                           \n" +
					"	// Height is represented in TENTHS of a meter                                           \n" +
					"	highp float height = (                                                                  \n" +
					"		texelColour.r * 255.0 * 256.0 * 256.0 +                                             \n" +
					"		texelColour.g * 255.0 * 256.0 +                                                     \n" +
					"		texelColour.b * 255.0 )                                                             \n" +
					"	-100000.0;                                                                              \n" +
					"                                                                                           \n" +
					"	vec4 floodColour;                                                                       \n" +
					"	if (height > 100.0) {                                                                   \n" +
					"		// High (>10m) over ground, transparent                                             \n" +
					"		floodColour = vec4(0.5, 0.5, 0.5, 0.0);                                             \n" +
					"	} else if (height > 50.0) {                                                             \n" +
					"		// Over ground but somewhat close to sea level, yellow                              \n" +
					"		floodColour = vec4(0.9, 0.9, 0.5, 0.4);                                             \n" +
					"	} else if (height > 0.0) {                                                              \n" +
					"		// Over ground but very close to sea level, red                                     \n" +
					"		floodColour = vec4(0.9, 0.5, 0.5, 0.4);                                             \n" +
					"	} else {                                                                                \n" +
					"		// Water, some semiopaque blue                                                      \n" +
					"		floodColour = vec4(0.05, 0.1, 0.9, 0.4);                                            \n" +
					"	}                                                                                       \n" +
					"                                                                                           \n" +
291
					"	// Now fetch color from texture 0, which is the basemap                                 \n" +
292 293
					"	texelColour = texture2D(uTexture0, vec2(vTextureCoords.s, vTextureCoords.t));           \n" +
					"                                                                                           \n" +
294 295
					"	// And compose them                                                                     \n" +
					"	floodColour = vec4(                                                                     \n" +
296
					"		texelColour.rgb * (1.0 - floodColour.a) +                                           \n" +
297 298 299 300 301 302
					"		floodColour.rgb * floodColour.a,                                                    \n" +
					"		1);                                                                                 \n" +
					"	                                                                                        \n" +
					"	// Last, fetch color from texture 1, which is the labels                                \n" +
					"	texelColour = texture2D(uTexture1, vec2(vTextureCoords.s, vTextureCoords.t));           \n" +
					"                                                                                           \n" +
303
					"	// And compose the labels on top of everything                                          \n" +
304
					"	gl_FragColor = vec4(                                                                    \n" +
305
					"		floodColour.rgb * (1.0 - texelColour.a) +                                           \n" +
306 307
					"		texelColour.rgb * texelColour.a,                                                    \n" +
					"		1);                                                                                 \n" +
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
					"}                                                                                          \n"
			},

			"Hypsometric tint": {
				tiles: ['https://{s}.tiles.mapbox.com/v4/mapbox.terrain-rgb/{z}/{x}/{y}.pngraw?access_token=' + mapboxAccessToken],
				shader:
					"void main(void) {                                                                          \n" +
					"	highp vec4 texelColour = texture2D(uTexture0, vec2(vTextureCoords.s, vTextureCoords.t));\n" +
					"                                                                                           \n" +
					"	// Color ramp. The alpha value represents the elevation for that RGB colour stop.       \n" +
					"	vec4 colours[5];                                                                        \n" +
					"	colours[0] = vec4(.1, .1, .5, 0.);                                                      \n" +
					"	colours[1] = vec4(.4, .55, .3, 1.);                                                     \n" +
					"	colours[2] = vec4(.9, .9, .6, 5000.);                                                   \n" +
					"	colours[3] = vec4(.6, .4, .3, 20000.);                                                  \n" +
					"	colours[4] = vec4(1., 1., 1., 40000.);                                                  \n" +
					"                                                                                           \n" +
					"	// Height is represented in TENTHS of a meter                                           \n" +
					"	highp float height = (                                                                  \n" +
					"		texelColour.r * 255.0 * 256.0 * 256.0 +                                             \n" +
					"		texelColour.g * 255.0 * 256.0 +                                                     \n" +
					"		texelColour.b * 255.0 )                                                             \n" +
					"	-100000.0;                                                                              \n" +
					"                                                                                           \n" +
					"	gl_FragColor.rgb = colours[0].rgb;                                                      \n" +
					"                                                                                           \n" +
					"	for (int i=0; i < 4; i++) {                                                             \n" +
					"		// Do a smoothstep of the heights between steps. If the result is > 0               \n" +
					"		// (meaning \"the height is higher than the lower bound of this step\"),            \n" +
					"		// then replace the colour with a linear blend of the step.                         \n" +
					"		// If the result is 1, this means that the real colour will be applied              \n" +
					"		// in a later loop.                                                                 \n" +
					"                                                                                           \n" +
					"		gl_FragColor.rgb = mix(                                                             \n" +
					"			gl_FragColor.rgb,                                                               \n" +
					"			colours[i+1].rgb,                                                               \n" +
					"			smoothstep( colours[i].a, colours[i+1].a, height )                              \n" +
					"		);                                                                                  \n" +
					"	}                                                                                       \n" +
					"                                                                                           \n" +
					"	gl_FragColor.a = 1.;                                                                    \n" +
					"}                                                                                          \n"
350 351 352 353 354
			},

			"Edge detection": {
				tiles: ['https://{s}.tiles.mapbox.com/v4/mapbox.satellite/{z}/{x}/{y}.png?access_token=' + mapboxAccessToken],
				shader:
355
					"const float distanceToNeighbourPixel = 1.0 / 256.0;                                      \n" +
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
					"const mat3 kernel = mat3(-1, -1, -1,    -1,  8, -1,     -1, -1, -1);                     \n" +
					"                                                                                         \n" +
					"// Try some other kernels by commenting/uncommenting lines:                              \n" +
					"// Emboss                                                                                \n" +
					"//const mat3 kernel = mat3(-2, -1,  0,       -1,  1,  1,    0,  1,  2);                  \n" +
					"                                                                                         \n" +
					"// Gaussian blur                                                                         \n" +
					"//const mat3 kernel = mat3( 0.045, 0.122, 0.045, 0.122, 0.332, 0.122, 0.045, 0.122, 0.045);  \n" +
					"                                                                                         \n" +
					"                                                                                         \n" +
					"void main(void) {                                                                        \n" +
					"	mat3 I;                                                                               \n" +
					"	float cnv[9];                                                                         \n" +
					"	vec4 sample;                                                                          \n" +
					"    vec3 acc = vec3(0,0,0);                                                              \n" +
					"	int i, j, c, p;                                                                       \n" +
					"                                                                                         \n" +
					"    // For each pixel in a 3x3 envelope around our core pixel                            \n" +
					"    for (int x=0; x<3; x++) {                                                            \n" +
					"      for (int y=0; y<3; y++) {                                                          \n" +
					"        sample = texture2D(uTexture0, vTextureCoords.st + vec2(x,y) * distanceToNeighbourPixel );  \n" +
					"                                                                                         \n" +
					"		acc += sample.rgb * kernel[x][y];                                                 \n" +
					"      }                                                                                  \n" +
					"    }                                                                                    \n" +
					"                                                                                         \n" +
					"	gl_FragColor = vec4(abs(acc), sample.a);                                              \n" +
					"                                                                                         \n" +
					"                                                                                         \n" +
					"    //gl_FragColor = vec4( (gl_FragColor.rgb * 0.5) + sample.rgb * 0.5, sample.a);       \n" +
					"}"
387 388
			},

389
			"Sentinel WMS: extract red": {
390 391 392
                bbox: L.latLngBounds([[40.478581086,0.143962175],[42.917929984,3.43994614]]),
				tiles: ['{ "wmsurl": "https://tiles.maps.eox.at/wms", "dpiMode": 7, "layers":"s2cloudless_3857", "srs":"epsg:3857" }'],
// 				tiles: ['{ "wmsurl": "http://geoserveis.icgc.cat/icgc_sentinel2/wms/service?", "layers":"sen2irc", "srs":"epsg:3857" }'],
393
				shader:
394
					"// Processed images from the ESA Sentinel satellites contain several sensor \n" +
395
					"// bands. This example isolates the visible red sensor data from a true colour \n" +
396
					"// \n" +
397 398 399
// 					"// Images come from the ICGC WMS service. \n" +
// 					"// See http://www.icgc.cat/Administracio-i-empresa/Serveis/Geoinformacio-en-linia-Geoserveis/WMS-i-WMTS/WMS-de-cartografia-raster/WMS-WMS-Time-d-ortoimatges-Sentinel-2 for more info. \n" +
// 					"// \n" +
400 401 402
					"// The notation of WMS tilelayers is not standard. Please refer to the\n" +
					"// source code of the WMS example if you want to use WMS sources with TileLayer.GL.\n" +
					"\n" +
403 404 405
					"void main(void) {                                                                        \n" +
					"	vec4 texelColour = texture2D(uTexture0, vec2(vTextureCoords.s, vTextureCoords.t));    \n" +
					"                                                                                         \n" +
406 407 408
					"	float visibleRed = texelColour.r;                                                     \n" +
					"	float visibleGreen = texelColour.g;                                                   \n" +
					"	float visibleBlue = texelColour.b;                                                    \n" +
409
					"                                                                                         \n" +
410
					"	gl_FragColor = vec4(visibleRed, visibleRed, visibleRed, 1.0);                               \n" +
411 412
					"                                                                                         \n" +
					"}"
413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
// 			},
// 
// 			"Sentinel: on-the-fly NDWI": {
//                 bbox: L.latLngBounds([[40.478581086,0.143962175],[42.917929984,3.43994614]]),
// 				tiles: ['{ "wmsurl": "https://tiles.maps.eox.at/wms", "dpiMode": 7, "layers":"s2cloudless_3857", "srs":"epsg:3857" }'],
// 				shader:
// 					"// Processed images from the ESA Sentinel satellites contain several sensor             \n" +
// 					"// bands. This example calculates NDWI (Normalized Differential Water Index)            \n" +
// 					"// from a false-color image with a near-infrared channel.                               \n" +
// 					"//                                                                                      \n" +
// 					"// Images come from a sentinel-hub.com demo account.                                    \n" +
// 					"                                                                                        \n" +
// 					"void main(void) {                                                                       \n" +
// 					"	vec4 texelColour = texture2D(uTexture0, vec2(vTextureCoords.s, vTextureCoords.t));   \n" +
// 					"                                                                                        \n" +
// 					"	float infrared = texelColour.r;     // SENTINEL band 8                               \n" +
// 					"	float visibleRed = texelColour.g;   // SENTINEL band 4                               \n" +
// 					"	float visibleGreen = texelColour.b; // SENTINEL band 3                               \n" +
// 					"                                                                                        \n" +
// 					"	// Calcualte NDWI here                                                               \n" +
// 					"	float ndwi = (visibleGreen - infrared) / (visibleGreen + infrared);                  \n" +
// 					"                                                                                        \n" +
// 					"	if (ndwi >= 0.95) {                                                                  \n" +
// 					"		// If the NDWI is > 0.95, assume the pixel is water.                             \n" +
// 					"		gl_FragColor = vec4(0.0, 0.0, 1.0, 1.0);                                         \n" +
// 					"	} else {                                                                            \n" +
// 					"		// If the pixel is not water, diaplay a shade of green                           \n" +
// 					"		// Greener = more vegetation cover                                              \n" +
// 					"		gl_FragColor = vec4(0., 0.5-ndwi*2., 0.0, 1.0);                                  \n" +
// 					"    }                                                                                   \n" +
// 					"}"
// 			},
// 
// 			"Sentinel: half-true half-false color": {
//                 bbox: L.latLngBounds([[40.478581086,0.143962175],[42.917929984,3.43994614]]),
// 				tiles: ['http://services.sentinel-hub.com/v1/wmts/' + sentinelhubKey + '?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&Layer=COLOR_INFRARED&TileMatrixSet=PopularWebMercator256&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&FORMAT=image/jpg&showLogo=false',
// 				'http://services.sentinel-hub.com/v1/wmts/' + sentinelhubKey + '?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&Layer=TRUE_COLOR&TileMatrixSet=PopularWebMercator256&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&FORMAT=image/jpg&showLogo=false'
// 				],
// 				shader:
//                     "// Processed images from the SENTINEL satellites contain several sensor                 \n" +
// 					"// bands. This example takes a true color and an infrared false color image             \n" +
// 					"// and shows an image in-between those two.                                             \n" +
// 					"//                                                                                      \n" +
// 					"// Experiment changing the value of percentTrueColor!                                   \n" +
// 					"//                                                                                      \n" +
// 					"// Images come from a sentinel-hub.com demo account.                                    \n" +
// 					"                                                                                        \n" +
// 					"void main(void) {                                                                       \n" +
// 					"	vec4 texelColourA = texture2D(uTexture0, vec2(vTextureCoords.s, vTextureCoords.t));  \n" +
// 					"	vec4 texelColourB = texture2D(uTexture1, vec2(vTextureCoords.s, vTextureCoords.t));  \n" +
// 					"                                                                                        \n" +
// 					"	float infrared     = texelColourA.r; // SENTINEL band 8                              \n" +
// 					"	float visibleRed   = texelColourB.r; // SENTINEL band 4                              \n" +
// 					"	float visibleGreen = texelColourB.g; // SENTINEL band 3                              \n" +
// 					"	float visibleBlue  = texelColourB.b; // SENTINEL band 2                              \n" +
// 					"                                                                                        \n" +
// 					"	vec3 trueColor = vec3(visibleRed, visibleGreen, visibleBlue);                        \n" +
// 					"    vec3 falseColor = vec3(infrared, visibleRed, visibleGreen);                         \n" +
// 					"                                                                                        \n" +
// 					"	float percentTrueColor = 0.5;                                                        \n" +
// 					"                                                                                        \n" +
// 					"	vec3 color = trueColor * percentTrueColor + falseColor * (1.-percentTrueColor);      \n" +
// 					"                                                                                        \n" +
// 					"	gl_FragColor = vec4(color, 1.0);                                                     \n" +
// 					"}"
478 479
			}
		};
Iván Sánchez Ortega's avatar
Iván Sánchez Ortega committed
480

481 482 483 484 485 486 487 488 489 490 491 492 493 494
		// Fill up the demo selector

		var selector = document.getElementById('demo-selector');

		for (var i in demos) {
			var option = document.createElement('option');
			option.innerHTML = option.value = i;

			if (i === "Basic colour channel inversion") {
				option.selected = true;
			}

			selector.appendChild(option);
		}
Iván Sánchez Ortega's avatar
Iván Sánchez Ortega committed
495

496 497
		selector.addEventListener('change', function(ev){
			tileServersMirror.setValue(  demos[ selector.value ].tiles.join('\n') );
Iván Sánchez Ortega's avatar
Iván Sánchez Ortega committed
498

499 500 501 502
			var code = demos[ selector.value ].shader;
			var lines = code.split('\n');
			lines = lines.map(function(str) { return str.trimRight(); });
			fragmentCodeMirror.setValue( lines.join('\n') );
503 504 505 506 507 508 509 510 511
			
			var bbox = demos[ selector.value ].bbox;
			if (bbox) {
// 				map.flyToBounds(bbox);
				map.fitBounds(bbox);
			} else {
// 				map.flyToBounds(L.latLngBounds( [[-90, -180], [90, 180]] ));
				map.fitBounds(L.latLngBounds( [[-90, -180], [90, 180]] ));
			}
512 513 514 515 516 517 518
		});


		var map = L.map('map').fitWorld();
		var tileGlLayer;

		// Function that will (re-)trigger the TileLayer.GL creation whenever the shader or the tile list is modified
Iván Sánchez Ortega's avatar
Iván Sánchez Ortega committed
519
		function redo() {
520 521
			document.getElementById('error-modal').style.display = 'none';

522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542
			var tileUrls = tileServersMirror.getValue().split('\n')
                .filter(function(i){ return i.trim().length; });

			// Replace the hackish JSON definitions for WMS layers into actual instances of `L.TileLayer`
            var tileLayers = tileUrls.map(function(str){
                try {
                    var wmsOptions = JSON.parse(str);
                    if (wmsOptions && wmsOptions.wmsurl) {
                        var url = wmsOptions.wmsurl;
                        delete wmsOptions.wmsurl;
                        wmsOptions.crs = map.options.crs;
                        var layer = L.tileLayer.wms(url, wmsOptions);
                        return layer;
                    } else {
                        return L.tileLayer(str);
                    }
                } catch(ex) {
                        return L.tileLayer(str);
                }
            });

Iván Sánchez Ortega's avatar
Iván Sánchez Ortega committed
543 544 545 546 547
			var tileUrlsLength = tileUrls.length;

			// Copy-pasted from _loadGLProgram, plus comments
			var fragmentShaderHeader =
				"precision highp float;       // Use 24-bit floating point numbers for everything\n" +
548
				"uniform float uNow;          // Microseconds since page load, as per performance.now()\n" +
549
				"varying vec2 vTextureCoords; // Pixel coordinates of this fragment, to fetch texture color\n" +
Iván Sánchez Ortega's avatar
Iván Sánchez Ortega committed
550 551 552 553 554 555 556 557 558 559
				"varying vec2 vCRSCoords;     // CRS coordinates of this fragment\n" +
				"varying vec2 vLatLngCoords;  // Lat-Lng coordinates of this fragment (linearly interpolated)";

			var length = 1;

			for (var i=0; i<tileUrlsLength && i<8; i++) {
				fragmentShaderHeader += "\nuniform sampler2D uTexture" + i + ";";
			}

			fragmentHeaderMirror.setValue( fragmentShaderHeader );
560
			fragmentHeaderMirror.setSize('100%', (4 + tileUrlsLength) + 'rem');
Iván Sánchez Ortega's avatar
Iván Sánchez Ortega committed
561 562 563 564 565 566 567 568
			fragmentCodeMirror.setOption('firstLineNumber', 5 + tileUrlsLength);

			if (tileGlLayer) {
				tileGlLayer.remove();
			}

			tileGlLayer = L.tileLayer.gl({
				fragmentShader: fragmentCodeMirror.getValue(),
569 570
				// tileUrls: tileUrls, // Legacy. Could be used when no WMS tilelayers
				tileLayers: tileLayers
571 572 573 574 575 576 577 578 579
			});

			var glError = tileGlLayer.getGlError();
			if (glError) {
				document.getElementById('error-modal').innerHTML = glError;
				document.getElementById('error-modal').style.display = 'block';
			} else {
				tileGlLayer.addTo(map);
			}
Iván Sánchez Ortega's avatar
Iván Sánchez Ortega committed
580

581 582 583 584
			tileGlLayer.on('tileerror', function(err){
                console.error('Error when loading tile: ', err);
			})

585
			onResize();
Iván Sánchez Ortega's avatar
Iván Sánchez Ortega committed
586 587 588 589 590 591
		}

		redo();
		fragmentCodeMirror.on('change', redo);
		tileServersMirror.on('change', redo);

592 593 594 595 596 597 598 599 600 601 602 603 604 605

		// Whenever the browser window resizes (and the content reflows),
		// or when the tile servers list changes (and the static fragment code
		// potentially changes length), calculate the size of the fragment code
		// editor to use up all available space
		function onResize() {
			var top = fragmentCodeMirror.getWrapperElement().offsetTop;
			var bottom = window.innerHeight;
			fragmentCodeMirror.setSize('100%', bottom - top);
		}

		window.addEventListener('resize', onResize);


Iván Sánchez Ortega's avatar
Iván Sánchez Ortega committed
606 607 608
	</script>
</body>
</html>