@metoceanapi/wxtiles-common 0.0.6 → 0.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1108 @@
1
+ import { __colorSchemes_default_preset } from "../defaults/colorschemes";
2
+ import { __colorStyles_default_preset } from "../defaults/styles";
3
+ import { __units_default_preset } from "../defaults/uconv";
4
+
5
+ /** x,y,z */
6
+ export interface XYZ {
7
+ x: number;
8
+ y: number;
9
+ z: number;
10
+ }
11
+
12
+ /** type for unit converter */
13
+ export type WxUnitTuple = [string, number, number?];
14
+
15
+ /** Type of an Object with all unit convertion tupels */
16
+ export interface WxUnits {
17
+ [unit: string]: WxUnitTuple | undefined;
18
+ }
19
+
20
+ /**
21
+ * Type of an Object with all color schemes,
22
+ * each color scheme is an array of colors evenly distributed between min and max values in a {@link WxLegend} and {@link RawCLUT}*/
23
+ export interface WxColorSchemes {
24
+ [name: string]: string[] | undefined;
25
+ }
26
+
27
+ /** A [level,color] tuple */
28
+ export type colorMapTuple = [number, string];
29
+
30
+ /** Weak color style (may not have all fields of {@link WxColorStyleStrict}) */
31
+ export interface WxColorStyleWeak extends Partial<WxColorStyleStrict> {}
32
+
33
+ /** interface of an object with all mixed color styles */
34
+ export interface WxColorStylesWeakMixed {
35
+ [name: string]: WxColorStyleWeak | WxColorStyleWeak[] | undefined;
36
+ }
37
+
38
+ /** interface of an object with all weak color styles */
39
+ export interface ColorStylesIncomplete {
40
+ [name: string]: WxColorStyleWeak | undefined;
41
+ }
42
+
43
+ /** Strict style interface */
44
+ export interface WxColorStyleStrict {
45
+ /** Name of the style */
46
+ name: string;
47
+
48
+ /** Name of a parent style to inherit from */
49
+ parent?: string;
50
+
51
+ /** Tile filling schema.
52
+ * - **'none'** means no fill, leave the tile transparent
53
+ * - **'solid'** means solid fill, no gradient between levels.
54
+ * - **'gradient'** means gradient fill.
55
+ * */
56
+ fill: "none" | "gradient" | "solid";
57
+
58
+ /**
59
+ * Color of isolines.
60
+ * - **'none'** do not render.
61
+ * - **'fill'** using value of {@link fill} in each pixel.
62
+ * - **'inverted'** using *inverted* value of {@link fill} in each pixel.
63
+ * - **'#RGB'** or '**#RRGGBB**' or '**#RRGGBBAA**' - using this WEB-color.
64
+ * */
65
+ isolineColor: "none" | "inverted" | "fill" | `#${string}`;
66
+
67
+ /** if true then render isoline text values */
68
+ isolineText: boolean;
69
+
70
+ /** Font size of isoline text values in ems */
71
+ isolineTextSizeEm: number;
72
+
73
+ /** if true then render a solid background behind isoline text values */
74
+ isolineTextBackground: boolean;
75
+
76
+ /**
77
+ * Representation of the wind/current field.
78
+ * - **'none'** do not render vectors.
79
+ * - **'arrows'** use arrows to represent winds/currents.
80
+ * - **'barbs'** use barbs.
81
+ * */
82
+ vectorType: "none" | "arrows" | "barbs";
83
+
84
+ /**
85
+ * Color of vectors.
86
+ * - **'none'** do not render vectors.
87
+ * - **'fill'** using value of {@link fill} in each pixel.
88
+ * - **'inverted'** using *inverted* value of {@link fill} in each pixel.
89
+ * - **'#RGB'** or '**#RRGGBB**' or '**#RRGGBBAA**' - using this WEB-color.
90
+ * */
91
+ vectorColor: "none" | "inverted" | "fill" | `#${string}`;
92
+
93
+ /** Factor for vectors length */
94
+ vectorFactor: number;
95
+
96
+ /**
97
+ * Draw streamlines:
98
+ * - **'none'** means no streamlines.
99
+ * - **'fill'** using value of {@link fill} in each pixel.
100
+ * - **'inverted'** using *inverted* value of {@link fill} in each pixel.
101
+ * - **'#RGB'** or '**#RRGGBB**' or '**#RRGGBBAA**' - using this WEB-color.
102
+ * */
103
+ streamLineColor: "none" | "inverted" | "fill" | `#${string}`;
104
+
105
+ /** factor to scale streamlines length */
106
+ streamLineSpeedFactor: number;
107
+
108
+ /**
109
+ * Step to seed streamlines. Streamlines spread both ways from seed point.
110
+ * less value means more streamlines.
111
+ * */
112
+ streamLineGridStep?: number;
113
+
114
+ /** steps in each streamline */
115
+ streamLineSteps?: number;
116
+
117
+ /**
118
+ * - if true then render streamlines as static lines.
119
+ * - if false then render streamlines as animated lines.
120
+ * */
121
+ streamLineStatic: boolean;
122
+
123
+ /** If true then fill values below style's minimum. */
124
+ showBelowMin: boolean;
125
+
126
+ /** If true then fill values above style's maximum. */
127
+ showAboveMax: boolean;
128
+
129
+ /** Color scheme name from the default set. May be extended in {@link WxAPI}*/
130
+ colorScheme: string;
131
+
132
+ /** Used if presented instead of colorScheme */
133
+ colors?: string[];
134
+
135
+ /**
136
+ * Used if presented instead of levels, colors, colorScheme.
137
+ * Array of [level,color] tuples. Colors are WEB-colors.
138
+ */
139
+ colorMap?: [number, string][];
140
+
141
+ /** Levels to build legend. Used if presented, otherwise 10 levels are calculated evenly on given data */
142
+ levels?: number[];
143
+
144
+ /** radius for the BOX filter */
145
+ blurRadius: number;
146
+
147
+ /** Additional rotation of all wind or current's vectors or directions by angle in degrees.*/
148
+ addDegrees: number;
149
+
150
+ /** Units of the style (from the default set)*/
151
+ units: string;
152
+
153
+ /**
154
+ * Additional extend of default {@link units}.
155
+ * @see {@link WxUnits}
156
+ * */
157
+ extraUnits?: WxUnits;
158
+
159
+ /**
160
+ * masking:
161
+ * - **'none'** - no masking.
162
+ * - **'sea'** - make sea transparent.
163
+ * - **'land'** - make land transparent.
164
+ * */
165
+ mask?: "land" | "sea" | "none";
166
+
167
+ /** If exists then try to use WebGL to render tiles */
168
+ gl?: {
169
+ animationSpeed?: number;
170
+ noiseTexturePow?: number;
171
+ vectorFieldFactor?: number;
172
+ animationIntensity?: number;
173
+ wavesCount?: number;
174
+ };
175
+ }
176
+
177
+ /**
178
+ * @typedef {Object} WxColorStylesStrict
179
+ * @property {string} name - name of the style
180
+ */
181
+ export interface WxColorStylesStrict {
182
+ base: WxColorStyleStrict;
183
+ [name: string]: WxColorStyleStrict | undefined;
184
+ }
185
+
186
+
187
+ /*const context = {
188
+ [_units: WxUnits]: __units_default_preset,
189
+ [_colorSchemes: WxColorSchemes]: null,
190
+ [_colorStylesUnrolled: WxColorStylesStrict]: null,
191
+ }
192
+ */
193
+ const context = {
194
+ _units: __units_default_preset,
195
+ _colorSchemes: __colorSchemes_default_preset,
196
+ _colorStylesUnrolled: __colorStyles_default_preset,
197
+ wxlogging: false,
198
+ }
199
+
200
+ /** Options for the wxtiles library */
201
+ export interface WxTilesLibOptions {
202
+ /** Additional Color styles to use for the library */
203
+ colorStyles?: WxColorStylesWeakMixed;
204
+
205
+ /** Additional color schemes to use for the library */
206
+ colorSchemes?: WxColorSchemes;
207
+
208
+ /** Additional units to use for the library */
209
+ units?: WxUnits;
210
+ }
211
+
212
+ /**
213
+ * Initialize the wxtiles library
214
+ * @param options - options {@link WxTilesLibOptions} to initialize the library
215
+ */
216
+ export function WxTilesLibSetup({
217
+ colorStyles = {},
218
+ units = {},
219
+ colorSchemes = {},
220
+ }: WxTilesLibOptions = {}): void {
221
+ WXLOG("WxTile lib setup: start");
222
+ context._units = Object.assign({}, __units_default_preset, units);
223
+ context._colorSchemes = Object.assign(
224
+ {},
225
+ colorSchemes,
226
+ __colorSchemes_default_preset,
227
+ );
228
+ const toUnroll = Object.assign({}, colorStyles, __colorStyles_default_preset);
229
+ context._colorStylesUnrolled = unrollStylesParent(toUnroll);
230
+ WXLOG("WxTile lib setup: styles unrolled");
231
+
232
+ // Make sure fonts are loaded & ready!
233
+ (async () => {
234
+ try {
235
+ await document.fonts.load("32px barbs");
236
+ await document.fonts.load("32px arrows");
237
+ } catch (e) {
238
+ WXLOG("WxTile lib setup: fonts not loaded");
239
+ }
240
+ })();
241
+
242
+ WXLOG("WxTile lib setup is done.");
243
+ }
244
+
245
+ /**
246
+ * Get all {@link WxColorStylesStrict} used by the library
247
+ * */
248
+ export function WxGetColorStyles(): WxColorStylesStrict {
249
+ return context._colorStylesUnrolled;
250
+ }
251
+
252
+ /**
253
+ * Get all {@link WxColorSchemes} used by the library
254
+ * */
255
+ export function WxGetColorSchemes(): WxColorSchemes {
256
+ return context._colorSchemes;
257
+ }
258
+
259
+ /** A function type with extra properties. */
260
+ export interface Converter {
261
+ /** interface of a function - unit cinverter*/
262
+ (x: number): number;
263
+ /** true if the converter is a trivial one */
264
+ trivial?: boolean;
265
+ }
266
+
267
+ /**
268
+ * Convert a value from one unit to another
269
+ * @param from - the unit to convert from
270
+ * @param to - the unit to convert to
271
+ * @param customUnits - custom units to use if needed
272
+ * @returns a function that converts a value from one unit to another
273
+ * @example
274
+ * ```ts
275
+ * const convert = makeConverter('m/s', 'km/h');
276
+ * const speed = convert(10); // speed is now 36
277
+ * ```
278
+ * */
279
+ export function makeConverter(
280
+ from: string,
281
+ to: string,
282
+ customUnits?: WxUnits,
283
+ ): Converter {
284
+ WXLOG("makeConverter: From=", from, " To=", to);
285
+ const c = (x: number) => x;
286
+ c.trivial = true;
287
+ if (from === to) {
288
+ WXLOG("Trivial converter");
289
+ return c; // trivial
290
+ }
291
+
292
+ const localUnitsCopy = Object.assign({}, context._units, customUnits);
293
+ const fromUnit = localUnitsCopy[from];
294
+ const toUnit = localUnitsCopy[to];
295
+ if (!fromUnit || !toUnit) {
296
+ WXLOG("Inconvertible units. Trivial converter");
297
+ return c; // Inconvertible
298
+ }
299
+
300
+ const [fromUnitBase, fromFactor, fromOffset] = fromUnit;
301
+ const [toUnitBase, toFactor, toOffset] = toUnit;
302
+
303
+ if (fromUnitBase !== toUnitBase || !fromFactor || !toFactor) {
304
+ WXLOG("Inconvertible units. Trivial converter");
305
+ return c; // trivial
306
+ }
307
+
308
+ const a = fromFactor / toFactor;
309
+ const b = ((fromOffset || 0) - (toOffset || 0)) / toFactor;
310
+ return b ? (x: number) => a * x + b : (x: number) => a * x;
311
+ }
312
+
313
+ /**
314
+ * Unroll color styles with parent references
315
+ * @param stylesArrInc - array of styles, some of them may be incomplete, with inheritence
316
+ * @returns Strict styles array
317
+ */
318
+ function unrollStylesParent(
319
+ stylesArrInc: WxColorStylesWeakMixed,
320
+ ): WxColorStylesStrict {
321
+ const stylesInc: ColorStylesIncomplete = Object.assign(
322
+ {},
323
+ __colorStyles_default_preset,
324
+ );
325
+ for (const name in stylesArrInc) {
326
+ const styleA = stylesArrInc[name];
327
+ if (Array.isArray(styleA)) {
328
+ for (let i = 0; i < styleA.length; ++i) {
329
+ stylesInc[`${name}[${i}]`] = Object.assign({}, styleA[i]); // deep copy
330
+ }
331
+ } else {
332
+ stylesInc[name] = Object.assign({}, styleA); // deep copy
333
+ }
334
+ }
335
+
336
+ const baseStyleCopy = Object.assign({}, __colorStyles_default_preset.base);
337
+ // recursive function to apply inheritance
338
+ const inherit = (
339
+ stylesInc: ColorStylesIncomplete,
340
+ name: string,
341
+ ): WxColorStyleStrict => {
342
+ if (name === "base") return baseStyleCopy; // nothing to inherit
343
+ const style = stylesInc[name]; // there are no arrays by this point
344
+ if (!style) return baseStyleCopy; // nothing to inherit
345
+ if (!style.parent || !(style.parent in stylesInc)) style.parent = "base";
346
+ const parent = inherit(stylesInc, style.parent); // After inheritance it is FULL ColorStyle
347
+ return Object.assign(
348
+ style,
349
+ Object.assign({}, parent, style, { parent: "base" }),
350
+ ); // this ugly construction changes style 'in place' so it is a soft-copy. huray!
351
+ };
352
+
353
+ const styles: WxColorStylesStrict = { base: baseStyleCopy };
354
+ for (const name in stylesInc) {
355
+ styles[name] = inherit(stylesInc, name);
356
+ }
357
+
358
+ return styles;
359
+ }
360
+
361
+ /** Function type to load image from URL, with additional properties */
362
+ // biome-ignore lint/suspicious/noExplicitAny: Suppressing for specific use case
363
+ type UriLoaderPromiseFunc<T> = (url: string, ...props: any[]) => Promise<T>;
364
+
365
+ export interface CachedUriLoaderPromiseFunc<T> extends UriLoaderPromiseFunc<T> {
366
+ // biome-ignore lint/suspicious/noExplicitAny: Suppressing for specific use case
367
+ (url: string, ...props: any): Promise<T>;
368
+ clearCache: () => void;
369
+ }
370
+
371
+ /** Makes a cachable function that loads image from URL, with additional properties */
372
+ export function cacheUriPromise<T>(
373
+ fn: UriLoaderPromiseFunc<T>,
374
+ ): CachedUriLoaderPromiseFunc<T> {
375
+ const cache = new Map<string, Promise<T>>();
376
+ // biome-ignore lint/suspicious/noExplicitAny: Suppressing for specific use case
377
+ const cachedFunc = (url: string, ...props: any[]): Promise<T> => {
378
+ const cached = cache.get(url);
379
+ if (cached) return cached;
380
+ const promise = fn(url, ...props);
381
+ // cache any result (even falures)
382
+ cache.set(url, promise);
383
+ // except aborted (images), so they could be reloaded
384
+ promise.catch((e) => e.name === "AbortError" && cache.delete(url));
385
+ return promise;
386
+ };
387
+
388
+ cachedFunc.clearCache = () => cache.clear();
389
+ return cachedFunc;
390
+ }
391
+
392
+ /**
393
+ * abortable 'loadImage'
394
+ * @param url - image url
395
+ * @param requestInit - fetch requestInit
396
+ * */
397
+ export async function loadImage(
398
+ url: string,
399
+ requestInit?: RequestInit,
400
+ ): Promise<ImageBitmap> {
401
+ //// Method 0
402
+ const f = await fetch(url, requestInit);
403
+ if (f.status !== 200 && f.status !== 304) {
404
+ throw {
405
+ name: "Tile loading failed",
406
+ reason: f.headers.get("x-reason"),
407
+ status: f.status,
408
+ };
409
+ }
410
+
411
+ return await createImageBitmap(await f.blob(), { premultiplyAlpha: "none" });
412
+
413
+ // //// Method 000
414
+ // const img = new Image();
415
+ // img.src = URL.createObjectURL(await (await fetch(url, requestInit)).blob());
416
+ // await img.decode();
417
+ // URL.revokeObjectURL(img.src);
418
+ // return img;
419
+
420
+ // const img = new Image();
421
+ // img.crossOrigin = 'anonymous'; // essential
422
+ // const abortFunc = () => (img.src = ''); // stop loading
423
+ // signal.addEventListener('abort', abortFunc);
424
+
425
+ // //// Method 1
426
+ // img.src = url;
427
+ // await img.decode();
428
+ // signal.removeEventListener('abort', abortFunc);
429
+ // return img;
430
+
431
+ //// Method 2
432
+ // return new Promise((resolve, reject) => {
433
+ // img.onerror = (e) => {
434
+ // signal.removeEventListener('abort', abortFunc);
435
+ // reject(e);
436
+ // };
437
+ // img.onload = () => {
438
+ // signal.removeEventListener('abort', abortFunc);
439
+ // resolve(img);
440
+ // };
441
+ // img.src = url; // should be after .onload
442
+ // });
443
+ }
444
+
445
+ /** integral pare for fast box blur algorithm */
446
+ export interface IntegralPare {
447
+ /** Integral image */
448
+ integral: Uint32Array;
449
+ /** Integral image of ZEROs */
450
+ integralNZ: Uint32Array | null;
451
+ }
452
+
453
+ /** interface of a data read from a PNG tile */
454
+ export interface DataPicture {
455
+ raw: Uint16Array;
456
+ dmin: number;
457
+ dmax: number;
458
+ dmul: number;
459
+ }
460
+
461
+ /** One (scalar) or three (vector components + length component) {@link DataPictures} */
462
+ export type DataPictures =
463
+ | [DataPicture]
464
+ | [DataPicture, DataPicture, DataPicture];
465
+
466
+ /**
467
+ * class implements {@link DataPictures} with lazy calculation of {@link IntegralPare} for fast box blur algorithm
468
+ * */
469
+ export class DataIntegral implements DataPicture {
470
+ protected integral_?: IntegralPare;
471
+ radius = 0;
472
+ constructor(
473
+ public raw: Uint16Array,
474
+ public dmin: number,
475
+ public dmax: number,
476
+ public dmul: number,
477
+ ) {}
478
+ get integral(): IntegralPare {
479
+ if (!this.integral_) {
480
+ this.integral_ = buildIntegralPare(this.raw);
481
+ }
482
+ return this.integral_;
483
+ }
484
+ }
485
+
486
+ /** One (scalar) or two (vector) {@link DataIntegral} */
487
+ export type DataIntegrals = [DataIntegral] | [DataIntegral, DataIntegral];
488
+
489
+ /**
490
+ * Helper function to create a 2D canvas context
491
+ * @param width - width of the context
492
+ * @param height - height of the context
493
+ * @param willReadFrequently - if true, the context will be read frequently (browser will optimize it)
494
+ * @returns canvas context
495
+ */
496
+ export function create2DContext(
497
+ width: number,
498
+ height: number,
499
+ willReadFrequently = true,
500
+ ): CanvasRenderingContext2D {
501
+ const context = Object.assign(document.createElement("canvas"), {
502
+ width,
503
+ height,
504
+ imageSmoothingEnabled: false,
505
+ }).getContext("2d", {
506
+ willReadFrequently,
507
+ });
508
+ if (!context) throw new Error("Cannot get canvas context");
509
+ return context;
510
+ }
511
+
512
+ /** Converts an ImageBitmap to ImageData */
513
+ function imageToData(image: ImageBitmap): ImageData {
514
+ const { width, height } = image;
515
+ const context = create2DContext(width, height);
516
+ context.drawImage(image, 0, 0);
517
+ return context.getImageData(0, 0, width, height);
518
+ }
519
+
520
+ /**
521
+ * Load ImageData to from URL with RequestInit
522
+ * @param url - image url
523
+ * @param requestInit - fetch requestInit
524
+ * @returns Promise of ImageData
525
+ */
526
+ export async function loadImageData(
527
+ url: string,
528
+ requestInit?: RequestInit,
529
+ ): Promise<ImageData> {
530
+ return imageToData(await loadImage(url, requestInit));
531
+ }
532
+
533
+ /**
534
+ * Calculates integral image of the image
535
+ * @param image - ImageData to calculate integral image of
536
+ * @returns integral image {@link DataIntegral}
537
+ * */
538
+ function dataToIntegral(imData: ImageData): DataIntegral {
539
+ if (imData.data[34] < 1) {
540
+ WXLOG(
541
+ "Warning: image is in too old format. Check the version of the Splitter.",
542
+ );
543
+ }
544
+
545
+ // picTile contains bytes RGBARGBARGBA ...
546
+ // we need RG and don't need BA, so output is a 16 byte array picData with every second value dropped.
547
+ const imbuf = new Uint16Array(imData.data.buffer);
548
+ const raw = new Uint16Array(imbuf.length / 2);
549
+ for (let i = 0; i < raw.length; i++) {
550
+ raw[i] = imbuf[i * 2];
551
+ }
552
+
553
+ // Min and Max values of the data are encoded as two floats saved in the first 8 pixels in Blue channel
554
+ const minmaxbuf = new Uint8Array(8);
555
+ for (let i = 0; i < 8; ++i) {
556
+ minmaxbuf[i] = imData.data[i * 4 + 2];
557
+ }
558
+
559
+ const view = new DataView(minmaxbuf.buffer);
560
+ const dmin = view.getFloat32(0, true);
561
+ const dmax = view.getFloat32(4, true);
562
+ const dmul = (dmax - dmin) / 65535;
563
+ // const integral = buildIntegralPare(raw);
564
+ // return new DataIntegral({ raw, dmin, dmax, dmul }, 0);
565
+ return new DataIntegral(raw, dmin, dmax, dmul);
566
+ }
567
+
568
+ /**
569
+ * Load {@link DataIntegral} from URL with RequestInit
570
+ * @param url - image url
571
+ * @param requestInit - fetch requestInit
572
+ * @returns Promise of {@link DataIntegral}
573
+ * */
574
+ export async function loadDataIntegral(
575
+ url: string,
576
+ requestInit?: RequestInit,
577
+ ): Promise<DataIntegral> {
578
+ return dataToIntegral(await loadImageData(url, requestInit));
579
+ }
580
+
581
+ /**
582
+ * Calculaates {@link IntegralPare} from raw data Uint16Array.
583
+ * Used for fast box-blur algo
584
+ * Integarl image: https://en.wikipedia.org/wiki/Summed-area_table.
585
+ * @param raw - raw data
586
+ * @returns IntegralPare
587
+ * */
588
+ export function buildIntegralPare(raw: Uint16Array): IntegralPare {
589
+ const integral = new Uint32Array(258 * 258);
590
+ // The main Idea of integralNZ is to calculate the amount of Non Zero values,
591
+ // so in the Blur algorithm it can be used for 'averaging' instead of actual area of a BoxBlur frame
592
+ const integralNZ = new Uint32Array(258 * 258);
593
+
594
+ integral[0] = raw[0]; // upper left value
595
+ integralNZ[0] = raw[0] ? 1 : 0; // upper left value
596
+
597
+ // boundaries
598
+ for (let i = 1; i < 258; ++i) {
599
+ integral[i] = raw[i] + integral[i - 1]; // uper boundary
600
+ integralNZ[i] = (raw[i] ? 1 : 0) + integralNZ[i - 1]; // uper boundary
601
+ const yi = 258 * i;
602
+ integral[yi] = raw[yi] + integral[yi - 258]; // left boundary
603
+ integralNZ[yi] = (raw[yi] ? 1 : 0) + integralNZ[yi - 258]; // left boundary
604
+ }
605
+
606
+ // the rest picture
607
+ for (let y = 1; y < 258; ++y) {
608
+ for (let x = 1; x < 258; ++x) {
609
+ const i = 258 * y + x;
610
+ integral[i] =
611
+ raw[i] + integral[i - 258] + integral[i - 1] - integral[i - 259];
612
+ integralNZ[i] =
613
+ (raw[i] ? 1 : 0) +
614
+ integralNZ[i - 258] +
615
+ integralNZ[i - 1] -
616
+ integralNZ[i - 259];
617
+ }
618
+ }
619
+
620
+ // 66564 is the maximum posible value of the integralNZ image, so if all values are not 0, then no need to use it
621
+ return {
622
+ integral,
623
+ integralNZ: integralNZ[66563] === 66564 ? null : integralNZ,
624
+ };
625
+ }
626
+
627
+ // restore raw data from integral using zero radius
628
+ function restoreRawFromIntegral(im: DataIntegral): DataIntegral {
629
+ // TESTED - works
630
+ /*
631
+ \ 012345
632
+ 0 -AB---
633
+ 1 -CD--- - (2,1) r=0
634
+ 2 ------
635
+ */
636
+ const { integral: I } = im.integral;
637
+ im.raw[0] = I[0]; // upper left value
638
+ // the rest picture
639
+ for (let y = 1; y < 258; y++) {
640
+ im.raw[y] = I[y] - I[y - 1]; // uper boundary
641
+ im.raw[258 * y] = I[258 * y] - I[258 * (y - 1)]; // left boundary
642
+ for (let x = 1; x < 258; x++) {
643
+ const i = 258 * y + x;
644
+ im.raw[i] = I[i - 259] + I[i] - I[i - 258] - I[i - 1];
645
+ }
646
+ }
647
+
648
+ return im;
649
+ }
650
+
651
+ /**
652
+ * BoxBlur implementation based on integral image {@link DataIntegral}.
653
+ * Adaptaion of using in 'tiling' mode. Uses only one boudary line for each tile.
654
+ * Gives decent visual results, but not as good as bluring over the whole image.
655
+ * Sometimes distortion of the image is noticable on the edges of the tiles.
656
+ * Also it doesn't change/blur corners of the tiles.
657
+ * @param data - {@link DataIntegral}
658
+ * @param radius - radius for the box-blur algorithm
659
+ * */
660
+ export function blurData(im: DataIntegral, radius: number): DataIntegral {
661
+ const adjustedRadius = radius < 0 ? 0 : radius;
662
+ if (adjustedRadius === im.radius) return im;
663
+ im.radius = adjustedRadius;
664
+ if (!adjustedRadius) return restoreRawFromIntegral(im); // radius === 0
665
+
666
+ const { integral, integralNZ } = im.integral;
667
+
668
+ // process picture excluding two lines of boundaries
669
+ for (let y = 2; y < 256; y++) {
670
+ for (let x = 2; x < 256; x++) {
671
+ const i = 258 * y + x;
672
+ if (!im.raw[i]) {
673
+ continue;
674
+ }
675
+
676
+ /* |
677
+ 012345
678
+ 0 A--B--
679
+ 1 -+++--
680
+ 2 -+o+-- - (2,2) r=1
681
+ 3 C++D--
682
+ 4 ------
683
+
684
+ |
685
+ (25)34567
686
+ 253 -A--B-
687
+ 254 --+++-
688
+ 255 --+o+- - (255,255) r=1
689
+ 256 -C++D-
690
+ 257 ------
691
+
692
+ */
693
+
694
+ const rx = Math.min(adjustedRadius, x - 1, 256 - x);
695
+ const ry = Math.min(adjustedRadius, y - 1, 256 - y);
696
+
697
+ const i1 = 258 * (y - ry - 1) + x;
698
+ const i2 = 258 * (y + ry) + x;
699
+ let sumNZ: number;
700
+ if (integralNZ) {
701
+ const ANZ = integralNZ[i1 - rx - 1];
702
+ const BNZ = integralNZ[i1 + rx];
703
+ const CNZ = integralNZ[i2 - rx - 1];
704
+ const DNZ = integralNZ[i2 + rx];
705
+ sumNZ = ANZ + DNZ - BNZ - CNZ; // amount of non Zero values
706
+ } else {
707
+ sumNZ = (2 * rx + 1) * (2 * ry + 1); // all values are non Zero
708
+ }
709
+
710
+ const A = integral[i1 - rx - 1];
711
+ const B = integral[i1 + rx];
712
+ const C = integral[i2 - rx - 1];
713
+ const D = integral[i2 + rx];
714
+ const sum = A + D - B - C;
715
+
716
+ im.raw[i] = sum / sumNZ;
717
+ }
718
+ }
719
+
720
+ // process boundaries
721
+ // Copy the first line from the boundary to the second line, to make life easier
722
+ for (let k = 2; k < 256; k++) {
723
+ // top two lines
724
+ const ti = 258 + k; // start with (2,1)
725
+ if (im.raw[ti]) {
726
+ /*
727
+ |
728
+ 012345
729
+ A B
730
+ 0 -+++--
731
+ 1 C+oD-- - (2,1) rx=1, A=B=0
732
+ 2 ------
733
+
734
+ |
735
+ (25)4567
736
+ A B
737
+ 0 ---+++
738
+ 1 --C+oD - (256,1) rx=1, A=B=0
739
+ 2 ------
740
+
741
+ |
742
+ 012345
743
+ A B
744
+ 0 -+++++--
745
+ 1 C++o+D-- - (3,1) rx=2, A=B=0
746
+ 2 --------
747
+
748
+ |
749
+ (25)234567
750
+ A B
751
+ 0 -+++++
752
+ 1 C++o+D - (255,1) rx=2, A=B=0
753
+ 2 ------
754
+ */
755
+
756
+ const x = k;
757
+ const rx = Math.min(adjustedRadius, x - 1, 256 - x);
758
+
759
+ const i2 = 258 + x;
760
+ let sumNZ: number;
761
+ if (integralNZ) {
762
+ const ANZ = 0;
763
+ const BNZ = 0;
764
+ const CNZ = integralNZ[i2 - rx - 1];
765
+ const DNZ = integralNZ[i2 + rx];
766
+ sumNZ = ANZ + DNZ - BNZ - CNZ; // amount of non Zero values
767
+ } else {
768
+ sumNZ = (2 * rx + 1) * 2; // all values are non Zero
769
+ }
770
+
771
+ const A = 0;
772
+ const B = 0;
773
+ const C = integral[i2 - rx - 1];
774
+ const D = integral[i2 + rx];
775
+ const sum = A + D - B - C;
776
+
777
+ const s = sum / sumNZ;
778
+
779
+ im.raw[ti - 258] = s; // 0 line
780
+ im.raw[ti] = s; // 1 line
781
+ } // top
782
+
783
+ // bottom two lines
784
+ const bi = 258 * 256 + k;
785
+ if (im.raw[bi]) {
786
+ /*
787
+ |
788
+ 012345
789
+ 254 ------
790
+ 255 A--B--
791
+ 256 -+o+-- - (2,256) ry=1
792
+ 257 C++D--
793
+
794
+ |
795
+ 012345
796
+ 254 --------
797
+ 255 A----B--
798
+ 256 -++o++-- - (3,256) ry=2
799
+ 257 C++++D--
800
+ */
801
+ const x = k;
802
+ const rx = Math.min(adjustedRadius, x - 1, 256 - x);
803
+ const i1 = 258 * 255 + x;
804
+ const i2 = 258 * 257 + x;
805
+ const A = integral[i1 - rx - 1];
806
+ const B = integral[i1 + rx];
807
+ const C = integral[i2 - rx - 1];
808
+ const D = integral[i2 + rx];
809
+ const sum = A + D - B - C;
810
+
811
+ let sumNZ: number;
812
+ if (integralNZ) {
813
+ const ANZ = integralNZ[i1 - rx - 1];
814
+ const BNZ = integralNZ[i1 + rx];
815
+ const CNZ = integralNZ[i2 - rx - 1];
816
+ const DNZ = integralNZ[i2 + rx];
817
+ sumNZ = ANZ + DNZ - BNZ - CNZ; // amount of non Zero values
818
+ } else {
819
+ sumNZ = (2 * rx + 1) * 2; // all values are non Zero
820
+ }
821
+
822
+ const s = sum / sumNZ;
823
+ im.raw[bi] = s; // 256 row
824
+ im.raw[bi + 258] = s; // 257 row
825
+ } // bottom
826
+
827
+ // left two lines
828
+ const li = 258 * k + 1;
829
+ if (im.raw[li]) {
830
+ const y = k;
831
+ const ry = Math.min(adjustedRadius, y - 1, 256 - y);
832
+ const i1 = 258 * (y - ry - 1) + 1;
833
+ const i2 = 258 * (y + ry) + 1;
834
+
835
+ let sumNZ: number;
836
+ if (integralNZ) {
837
+ const ANZ = 0;
838
+ const BNZ = integralNZ[i1];
839
+ const CNZ = 0;
840
+ const DNZ = integralNZ[i2];
841
+ sumNZ = ANZ + DNZ - BNZ - CNZ; // amount of non Zero values
842
+ } else {
843
+ sumNZ = (2 * ry + 1) * 2; // all values are non Zero
844
+ }
845
+
846
+ const A = 0;
847
+ const B = integral[i1];
848
+ const C = 0;
849
+ const D = integral[i2];
850
+ const sum = A + D - B - C;
851
+
852
+ const s = sum / sumNZ;
853
+ im.raw[li - 1] = s; // 0 column
854
+ im.raw[li] = s; // 1 column
855
+ } // left
856
+
857
+ // right two lines
858
+ const ri = 258 * k + 256;
859
+ if (im.raw[ri]) {
860
+ const y = k;
861
+ const ry = Math.min(adjustedRadius, y - 1, 256 - y);
862
+ const i1 = 258 * (y - ry - 1) + 256;
863
+ const i2 = 258 * (y + ry) + 256;
864
+
865
+ let sumNZ: number;
866
+ if (integralNZ) {
867
+ const ANZ = integralNZ[i1 - 1];
868
+ const BNZ = integralNZ[i1 + 1];
869
+ const CNZ = integralNZ[i2 - 1];
870
+ const DNZ = integralNZ[i2 + 1];
871
+ sumNZ = ANZ + DNZ - BNZ - CNZ; // amount of non Zero values
872
+ } else {
873
+ sumNZ = 2 * (2 * ry + 1); // all values are non Zero
874
+ }
875
+
876
+ const A = integral[i1 - 1];
877
+ const B = integral[i1 + 1];
878
+ const C = integral[i2 - 1];
879
+ const D = integral[i2 + 1];
880
+ const sum = A + D - B - C;
881
+
882
+ const s = sum / sumNZ;
883
+ im.raw[ri] = s; // 256 column
884
+ im.raw[ri + 1] = s; // 257 column
885
+ } // right
886
+ } // for k
887
+
888
+ return im;
889
+ }
890
+
891
+ /**
892
+ * Convert Uin32 RGB color to web color
893
+ * @param color - Uin32 color
894
+ * @returns web color in format '#RRGGBB'
895
+ * */
896
+ export function RGBtoHEX(rgb: number): string {
897
+ const r = (rgb >> 0) & 255;
898
+ const g = (rgb >> 8) & 255;
899
+ const b = (rgb >> 16) & 255;
900
+ let rs = r.toString(16);
901
+ let gs = g.toString(16);
902
+ let bs = b.toString(16);
903
+ rs = rs.length === 2 ? rs : `0${rs}`;
904
+ gs = gs.length === 2 ? gs : `0${gs}`;
905
+ bs = bs.length === 2 ? bs : `0${bs}`;
906
+ return `#${rs}${gs}${bs}`;
907
+ }
908
+
909
+ /**
910
+ * Convert Uin32 RGBA color to web color
911
+ * @param color - Uin32 color
912
+ * @returns web color in format '#RRGGBBAA'
913
+ * */
914
+ export function RGBAtoHEX(rgba: number): string {
915
+ const r = (rgba >> 0) & 255;
916
+ const g = (rgba >> 8) & 255;
917
+ const b = (rgba >> 16) & 255;
918
+ const a = (rgba >> 24) & 255;
919
+ let rs = r.toString(16);
920
+ let gs = g.toString(16);
921
+ let bs = b.toString(16);
922
+ let as = a.toString(16);
923
+ rs = rs.length === 2 ? rs : `0${rs}`;
924
+ gs = gs.length === 2 ? gs : `0${gs}`;
925
+ bs = bs.length === 2 ? bs : `0${bs}`;
926
+ as = as.length === 2 ? as : `0${as}`;
927
+ return `#${rs}${gs}${bs}${as}`;
928
+ }
929
+
930
+ /**
931
+ * Convert web color to Uin32 RGB color
932
+ * @param color - web color in format '#RGB' or '#RRGGBB' or '#RRGGBBAA'
933
+ * @returns Uin32 color
934
+ * */
935
+ export function HEXtoRGBA(c: string): number {
936
+ if (c[0] === "#") {
937
+ if (c.length === 4)
938
+ return +(`0xff${c[3]}${c[3]}${c[2]}${c[2]}${c[1]}${c[1]}`);
939
+ if (c.length === 7)
940
+ return +(`0xff${c[5]}${c[6]}${c[3]}${c[4]}${c[1]}${c[2]}`);
941
+ if (c.length === 9)
942
+ return +(`0x${c[7]}${c[8]}${c[5]}${c[6]}${c[3]}${c[4]}${c[1]}${c[2]}`);
943
+ }
944
+
945
+ WXLOG("wrong color format", c);
946
+
947
+ return 0;
948
+ }
949
+
950
+ /**
951
+ * json loader helper
952
+ * @template {any} T - type of the object to load
953
+ * @param url - url to json file
954
+ * @param requestInit - requestInit for fetch
955
+ * @returns json object
956
+ * */
957
+ // biome-ignore lint/suspicious/noExplicitAny: Suppressing for specific use case
958
+ export async function fetchJson<T = any>(
959
+ url: RequestInfo,
960
+ requestInit?: RequestInit,
961
+ ): Promise<T> {
962
+ const response = await fetch(url, requestInit);
963
+ if (!response.ok) {
964
+ throw new Error(`error:${url} - ${response.statusText}`);
965
+ }
966
+
967
+ return response.json();
968
+ }
969
+
970
+ /**
971
+ * Create element helper
972
+ * @param tag - tag name
973
+ * @param className - class name
974
+ * @param container - container to append element
975
+ * @returns created element
976
+ * */
977
+ export function createEl(
978
+ tagName: string,
979
+ className = "",
980
+ container?: HTMLElement,
981
+ ): HTMLElement {
982
+ const el = document.createElement(tagName); // Object.assign(document.createElement(tagName), { className });
983
+ el.className = className;
984
+ container?.appendChild(el);
985
+ return el;
986
+ }
987
+
988
+ /**
989
+ * Color linear mixer
990
+ * @param color1 - color1 Uin32 RGBA
991
+ * @param color2 - color2 Uin32 RGBA
992
+ * @param k - koefficient
993
+ * @returns mixed color Uin32 RGBA
994
+ * */
995
+ export function mixColor(c1: number, c2: number, t: number): number {
996
+ const r1 = (c1 >> 0) & 255;
997
+ const g1 = (c1 >> 8) & 255;
998
+ const b1 = (c1 >> 16) & 255;
999
+ const a1 = c1 >>> 24;
1000
+
1001
+ const r2 = (c2 >> 0) & 255;
1002
+ const g2 = (c2 >> 8) & 255;
1003
+ const b2 = (c2 >> 16) & 255;
1004
+ const a2 = c2 >>> 24;
1005
+
1006
+ const r = r1 + t * (r2 - r1);
1007
+ const g = g1 + t * (g2 - g1);
1008
+ const b = b1 + t * (b2 - b1);
1009
+ const a = a1 + t * (a2 - a1);
1010
+ return r | (g << 8) | (b << 16) | (a << 24);
1011
+ }
1012
+
1013
+ /**
1014
+ * Helper to create array of levels for a style
1015
+ * @param min - min value
1016
+ * @param max - max value
1017
+ * @param n - number of levels
1018
+ * @returns array of levels
1019
+ * */
1020
+ export function createLevels(min: number, max: number, n: number): number[] {
1021
+ // create 10 levels from min to max
1022
+ const levels: number[] = [];
1023
+ for (let i = 0; i < n; ++i) {
1024
+ levels.push((i * (max - min)) / (n - 1) + min);
1025
+ }
1026
+ return levels;
1027
+ }
1028
+
1029
+ /**
1030
+ * Get closest existing time in array. If time is Date, strings will be converted to number to find closest time
1031
+ * @param times - array of times
1032
+ * @param time - time to find
1033
+ * @returns closest time a value from array
1034
+ * */
1035
+ export function getClosestTimeString(
1036
+ times: string[],
1037
+ time: Date | string | number,
1038
+ ): string {
1039
+ const unixTime: number =
1040
+ typeof time === "number"
1041
+ ? time
1042
+ : typeof time === "string"
1043
+ ? new Date(time).getTime()
1044
+ : time.getTime();
1045
+ // Take the next times[]'s after unixTime OR the last
1046
+ return (
1047
+ times.find((stime) => new Date(stime).getTime() >= unixTime) ||
1048
+ times[times.length - 1]
1049
+ );
1050
+ }
1051
+
1052
+ /**
1053
+ * Logging helper
1054
+ * */
1055
+ // biome-ignore lint/suspicious/noExplicitAny: Suppressing for specific use case
1056
+ export let WXLOG = (...args: any[]) => {};
1057
+
1058
+ /**
1059
+ * Set logging on/off
1060
+ * @param logging - true to turn on logging
1061
+ * @example
1062
+ * WxTilesLogging(true); // turn on logging to console
1063
+ *
1064
+ * WxTilesLogging(false); // turn off logging
1065
+ *
1066
+ * WxTilesLogging(console.trace); // set logging using console.trace
1067
+ * */
1068
+ // biome-ignore lint/suspicious/noExplicitAny: Suppressing for specific use case
1069
+ export function WxTilesLogging(on?: boolean | ((...args: any[]) => void)) {
1070
+ context.wxlogging = !!on;
1071
+ console.log("WXLOGing", context.wxlogging);
1072
+ WXLOG = typeof on === "function" ? on : context.wxlogging ? console.log : () => {};
1073
+ }
1074
+
1075
+ /**
1076
+ * Helper to convert short form of web color from '#RGB' to '#RRGGBB'
1077
+ * @param color - web color in format '#RGB' or '#RRGGBB' or '#RRGGBBAA'
1078
+ * @returns web color in format '#RRGGBB'
1079
+ * */
1080
+ export function refineColor(c: string): string {
1081
+ // convert short form of color into long #25f => #2255ff
1082
+ return c[0] === "#" && c.length === 4
1083
+ ? `#${c[1]}${c[1]}${c[2]}${c[2]}${c[3]}${c[3]}`
1084
+ : c;
1085
+ }
1086
+
1087
+ /**
1088
+ * Helper to fill URI template with values
1089
+ * @param uri - URI template
1090
+ * @param values - {@link XYZ} values to fill template
1091
+ * @returns URI with values filled
1092
+ * */
1093
+ export function uriXYZ(uri: string, { x, y, z }: XYZ): string {
1094
+ return uri
1095
+ .replace("{x}", `${x}`)
1096
+ .replace("{y}", `${y}`)
1097
+ .replace("{z}", `${z}`);
1098
+ // return uri.replace('{x}', x.toString()).replace('{y}', y.toString()).replace('{z}', z.toString());
1099
+ }
1100
+
1101
+ /**
1102
+ * Calculate hash of {@link XYZ}
1103
+ * @param xyz - {@link XYZ} to calculate hash
1104
+ * @returns string hash
1105
+ * */
1106
+ export function HashXYZ({ x, y, z }: XYZ): string {
1107
+ return `${z}-${x}-${y}`;
1108
+ }