agglomerative-clustering 1.1.4 → 2.0.0-beta.1
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.
- package/README.md +164 -67
- package/dist/clustering.js +14 -2
- package/dist/clustering.wasm +0 -0
- package/dist/index.cjs +182 -161
- package/dist/index.d.ts +61 -11
- package/dist/index.mjs +182 -161
- package/package.json +8 -3
package/README.md
CHANGED
|
@@ -1,122 +1,219 @@
|
|
|
1
|
-
#
|
|
1
|
+
# agglomerative-clustering
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**Exact Ward colour quantization for JavaScript. Cluster an image once, then cut it to a palette of any size in under a millisecond.**
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
[](https://www.npmjs.com/package/agglomerative-clustering)
|
|
6
|
+
[](LICENSE)
|
|
7
|
+

|
|
6
8
|
|
|
7
|
-
|
|
9
|
+

|
|
8
10
|
|
|
9
|
-
|
|
10
|
-
- 🎨 Generate color palettes from raw images or clustering
|
|
11
|
-
- ✂️ Quantize images using clustering or palette data
|
|
12
|
-
- 🕹️ Async interface with lazy WASM initialization
|
|
13
|
-
- 💾 Works with `Uint8Array`, `Uint8ClampedArray`, and `ImageData` inputs (`rgb` or `rgba`)
|
|
14
|
-
- 📦 TypeScript declarations included
|
|
11
|
+
Most colour quantizers answer one question: *give me k colours*. Ask for a different k and they start over. This library builds the complete merge hierarchy of the image's colours with Ward's method, which merges whichever two colour groups add the least squared error. Every palette size is then a cut of that one tree:
|
|
15
12
|
|
|
16
|
-
|
|
13
|
+
- **Every palette size from one pass.** After clustering, a palette of any size takes about 0.4 ms. A colour-count slider, or a set of 8/16/32/64-colour variants, costs one clustering instead of one per size.
|
|
14
|
+
- **Palettes nest, in a stable order.** The 16-colour palette is the 32-colour one with pairs merged. Index 0 is always the dominant colour, and each larger palette is the previous one with one entry refined and one colour appended, so swatches don't jump around as the count changes.
|
|
15
|
+
- **Transparency-aware.** Pixels count in proportion to their opacity, so a logo's transparent background never ends up in its palette.
|
|
16
|
+
- **Accurate.** Across the 24 Kodak photos it has the lowest average error of the six JavaScript quantizers we benchmarked, at every palette size from 16 to 256.
|
|
17
|
+
- **Fast enough to be interactive.** A 768×512 photo takes about 100 ms exact, in RGB or OKLab, or about 30 ms with `precision: 6` at the same quality. That is level with or faster than libimagequant and 3.7–15× faster than image-q.
|
|
18
|
+
- **Small and portable.** 65 KB of WebAssembly with SIMD, Node and browsers, an async API, TypeScript types and no runtime dependencies. Output is deterministic.
|
|
19
|
+
|
|
20
|
+
**[Try the demo](#demo)**: drop in an image and drag the palette-size slider.
|
|
21
|
+
|
|
22
|
+
## Install
|
|
17
23
|
|
|
18
24
|
```sh
|
|
19
25
|
npm install agglomerative-clustering
|
|
20
26
|
```
|
|
21
27
|
|
|
22
|
-
##
|
|
28
|
+
## Quick start
|
|
23
29
|
|
|
24
|
-
|
|
30
|
+
```js
|
|
31
|
+
import { getPalette, quantize } from 'agglomerative-clustering';
|
|
25
32
|
|
|
26
|
-
|
|
27
|
-
//
|
|
28
|
-
|
|
33
|
+
// `image` is ImageData, a raw RGBA Uint8Array, or { data, format: 'rgb' | 'rgba' }
|
|
34
|
+
const palette = await getPalette(image, 8); // Uint8Array: [r, g, b, r, g, b, ...]
|
|
35
|
+
const reduced = await quantize(image, 16, { dither: true }); // same type as the input
|
|
36
|
+
```
|
|
29
37
|
|
|
30
|
-
|
|
31
|
-
ImageData
|
|
38
|
+
### Cluster once, cut anywhere
|
|
32
39
|
|
|
33
|
-
|
|
34
|
-
{
|
|
40
|
+
```js
|
|
41
|
+
import { getClustering, getPaletteFromClustering, quantizeWithPalette } from 'agglomerative-clustering';
|
|
42
|
+
|
|
43
|
+
const clustering = await getClustering(imageData); // the expensive step, done once
|
|
44
|
+
|
|
45
|
+
slider.oninput = async () => {
|
|
46
|
+
const k = Number(slider.value);
|
|
47
|
+
const palette = await getPaletteFromClustering(clustering, k); // ~0.4 ms for any k
|
|
48
|
+
const result = await quantizeWithPalette(imageData, palette); // ~5-12 ms for a 768×512 image
|
|
49
|
+
ctx.putImageData(result, 0, 0);
|
|
50
|
+
};
|
|
35
51
|
```
|
|
36
52
|
|
|
37
|
-
The
|
|
53
|
+
The clustering is a compact `Uint8Array` (a 4-byte header plus 9 bytes per distinct colour), so you can cache it or store it next to the image. It records the colour space it was made in, so `quantizeWithClustering` matches in the same space unless you say otherwise.
|
|
38
54
|
|
|
39
|
-
##
|
|
55
|
+
## How it compares
|
|
40
56
|
|
|
41
|
-
|
|
57
|
+
This table covers the 24 Kodak photos (768×512) at 64 colours. "Error vs ours" is mean squared error relative to this library, so 1.08× means 8% more error. Every palette is mapped to pixels the same way, so palettes are compared like for like. Times are medians per image, in WASM on Node 22.
|
|
42
58
|
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
59
|
+
| Library | PSNR | Error vs ours | One palette | Palettes at 16/64/128/256 |
|
|
60
|
+
|---|---|---|---|---|
|
|
61
|
+
| **agglomerative-clustering** | **35.72 dB** | **1.00×** | 97 ms | **99 ms** |
|
|
62
|
+
| agglomerative-clustering, `precision: 6` | 35.70 dB | 1.00× | 31 ms | 31 ms |
|
|
63
|
+
| libimagequant (pngquant's engine) | 35.39 dB | 1.08× | 134 ms | 552 ms |
|
|
64
|
+
| image-q Wu | 35.51 dB | 1.05× | 740 ms | 3387 ms |
|
|
65
|
+
| image-q NeuQuant | 34.41 dB | 1.35× | 609 ms | 3461 ms |
|
|
66
|
+
| MMCQ (color-thief's algorithm) | 32.53 dB | 2.08× | 24 ms | 120 ms |
|
|
67
|
+
| image-q RgbQuant | 31.95 dB | 2.38× | 385 ms | 1535 ms |
|
|
68
|
+
|
|
69
|
+
The `precision: 6` row comes from a separate run on the same machine. Full results at every palette size, on synthetic images too, with ΔE2000 and the method, are in [bench/COMPARISON.md](bench/COMPARISON.md). You can reproduce them with `node bench/run.js`.
|
|
46
70
|
|
|
47
|
-
|
|
48
|
-
const { data, info } = await sharp(path).raw().ensureAlpha().toBuffer({ resolveWithObject: true });
|
|
49
|
-
return { width: info.width, height: info.height, data: new Uint8Array(data.buffer) };
|
|
50
|
-
}
|
|
71
|
+
## Options
|
|
51
72
|
|
|
52
|
-
|
|
53
|
-
await sharp(data, { raw: { width, height, channels: 4 } }).toFile(path);
|
|
54
|
-
}
|
|
73
|
+
Every function that takes an image also takes an optional last argument of options. They are all off by default, and the defaults give the exact results shown above.
|
|
55
74
|
|
|
56
|
-
|
|
75
|
+
| Option | Applies to | Values | What it does |
|
|
76
|
+
|---|---|---|---|
|
|
77
|
+
| `precision` | clustering | `1`–`8`, default `8` | Groups colours that share their top `precision` bits per channel before clustering, at their mean colour. **`6` is about 3× faster on photos at practically the same quality** (−0.02 dB), and caps the work on images with huge numbers of colours. `5` is about 8× faster for a small loss. |
|
|
78
|
+
| `colorSpace` | clustering and mapping | `'rgb'` (default), `'oklab'` | `'oklab'` clusters and matches in [OKLab](https://bottosson.github.io/posts/oklab/), where distance tracks perceived difference. It gives lower ΔE2000 at 64+ colours and on smooth gradients, at the cost of PSNR. Use it when the result is for human eyes and you want 64 or more colours. At 16 colours, RGB is better. |
|
|
79
|
+
| `alpha` | clustering | `'weight'` (default), `'ignore'` | `'weight'` counts each RGBA pixel in proportion to its opacity: fully transparent pixels are ignored, and semi-transparent ones count partially. For opaque images, and images whose pixels are only fully opaque or fully transparent, this is exact pixel counting. `'ignore'` counts every pixel fully, as 1.x did. Alpha is always preserved in the output. |
|
|
80
|
+
| `dither` | mapping | `false` (default), `true`, or `0`–`1` | Serpentine Floyd–Steinberg error diffusion, with a strength from 0 to 1. Hides banding in gradients at low colour counts. It scores worse on per-pixel metrics such as PSNR, because the noise is the point. Error is diffused in the chosen `colorSpace`, and fully transparent pixels are left undithered. |
|
|
81
|
+
| `width` | mapping | integer | Needed for dithering when the image is a `Uint8Array`, or a `RawImage` without `width`. `ImageData` provides it. |
|
|
57
82
|
|
|
58
|
-
|
|
59
|
-
const { width, height, data } = await loadImage('example.png');
|
|
83
|
+
"Clustering" means `getClustering` and `getPalette`, "mapping" means `quantizeWithClustering` and `quantizeWithPalette`, and `quantize` takes both.
|
|
60
84
|
|
|
61
|
-
|
|
62
|
-
|
|
85
|
+
Measured on the Kodak photos:
|
|
86
|
+
|
|
87
|
+
| Setting | 16 colours ΔE2000 | 256 colours ΔE2000 | One 64-colour palette |
|
|
88
|
+
|---|---|---|---|
|
|
89
|
+
| default (`rgb`, exact) | **4.31** | 1.67 | 102 ms |
|
|
90
|
+
| `precision: 6` | **4.29** | 1.68 | 31 ms |
|
|
91
|
+
| `colorSpace: 'oklab'` | 4.46 | **1.60** | 104 ms |
|
|
92
|
+
| `colorSpace: 'oklab', precision: 6` | 4.44 | 1.61 | 39 ms |
|
|
93
|
+
| libimagequant, for reference | 4.38 | 1.61 | 147 ms |
|
|
94
|
+
|
|
95
|
+
```js
|
|
96
|
+
// Perceptual palettes for a photo, quickly
|
|
97
|
+
const palette = await getPalette(photo, 128, { colorSpace: 'oklab', precision: 6 });
|
|
63
98
|
|
|
64
|
-
|
|
99
|
+
// Retro look: 8 colours, dithered
|
|
100
|
+
const retro = await quantize(imageData, 8, { dither: true });
|
|
65
101
|
|
|
66
|
-
|
|
102
|
+
// Dithering a raw buffer needs its width
|
|
103
|
+
const out = await quantize(rgbaBytes, 32, { dither: 0.8, width: 640 });
|
|
67
104
|
```
|
|
68
105
|
|
|
69
|
-
|
|
106
|
+
## When to use it, and when not
|
|
107
|
+
|
|
108
|
+
**A good fit:**
|
|
109
|
+
- **Interactive tools where people choose the number of colours:** palette editors, posterisers, pixel-art, embroidery, paint-by-number and knitting pattern generators, and LED, e-ink or limited-palette displays.
|
|
110
|
+
- **Generating several palette sizes for the same image,** or storing one clustering and cutting it later.
|
|
111
|
+
- **When you want the most accurate palette for a given size,** for example as a starting point for vectorisation or flat-colour art.
|
|
112
|
+
|
|
113
|
+
**Probably not the right tool:**
|
|
114
|
+
- **Shrinking PNG files in a build pipeline.** Use [sharp](https://sharp.pixelplumbing.com/) or pngquant, which run libimagequant natively and are tuned for compression.
|
|
115
|
+
- **A handful of "dominant" swatches for a UI theme.** [color-thief](https://lokeshdhakar.com/projects/color-thief/) or [node-vibrant](https://github.com/Vibrant-Colors/node-vibrant) are lighter and pick vivid or salient colours rather than the lowest-error ones.
|
|
116
|
+
- **Palettes that need their own alpha values,** as palette PNGs with translucent entries do. Pixels are weighted by opacity, but palette colours are opaque RGB, and each pixel keeps its own alpha.
|
|
117
|
+
|
|
118
|
+
## Usage
|
|
119
|
+
|
|
120
|
+
### Browser (Canvas)
|
|
70
121
|
|
|
71
122
|
```js
|
|
72
123
|
import { quantize } from 'agglomerative-clustering';
|
|
73
124
|
|
|
74
|
-
const canvas = document.getElementById('canvas');
|
|
75
125
|
const ctx = canvas.getContext('2d');
|
|
76
126
|
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
|
|
77
127
|
|
|
78
|
-
//
|
|
79
|
-
const result = await quantize(imageData,
|
|
128
|
+
// ImageData in, ImageData out
|
|
129
|
+
const result = await quantize(imageData, 16, { dither: true });
|
|
80
130
|
ctx.putImageData(result, 0, 0);
|
|
81
131
|
```
|
|
82
132
|
|
|
83
|
-
###
|
|
133
|
+
### Node.js (with sharp)
|
|
84
134
|
|
|
85
135
|
```js
|
|
86
|
-
import {
|
|
136
|
+
import { quantize } from 'agglomerative-clustering';
|
|
137
|
+
import sharp from 'sharp';
|
|
138
|
+
|
|
139
|
+
const { data, info } = await sharp('photo.jpg').ensureAlpha().raw().toBuffer({ resolveWithObject: true });
|
|
140
|
+
const image = { data: new Uint8Array(data.buffer, data.byteOffset, data.length), format: 'rgba', width: info.width };
|
|
87
141
|
|
|
88
|
-
const data =
|
|
142
|
+
const { data: output } = await quantize(image, 32, { precision: 6, dither: true });
|
|
89
143
|
|
|
90
|
-
|
|
91
|
-
|
|
144
|
+
await sharp(Buffer.from(output), { raw: { width: info.width, height: info.height, channels: 4 } }).toFile('photo-32.png');
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
## Input types
|
|
92
148
|
|
|
93
|
-
|
|
94
|
-
const palette4 = await getPaletteFromClustering(clustering, 4);
|
|
95
|
-
const palette16 = await getPaletteFromClustering(clustering, 16);
|
|
149
|
+
Every function that takes an image accepts:
|
|
96
150
|
|
|
97
|
-
|
|
98
|
-
|
|
151
|
+
```ts
|
|
152
|
+
Uint8Array // raw RGBA bytes
|
|
153
|
+
ImageData // from a canvas: always RGBA, width included
|
|
154
|
+
{ data: Uint8Array | Uint8ClampedArray, // explicit format, for RGB data or clamped arrays
|
|
155
|
+
format: 'rgb' | 'rgba',
|
|
156
|
+
width?: number, height?: number } // optional: used for dithering, copied to results
|
|
99
157
|
```
|
|
100
158
|
|
|
159
|
+
The `quantize*` functions return the same type they were given: a `Uint8Array` for a `Uint8Array`, `ImageData` for `ImageData`, and an object with the same `format` (plus `width`/`height` if given) for an object.
|
|
160
|
+
|
|
101
161
|
## API
|
|
102
162
|
|
|
163
|
+
### `getClustering(image, options?): Promise<Uint8Array>`
|
|
164
|
+
Builds the colour hierarchy for an image. Options: `colorSpace`, `precision`, `alpha`. Pass the result to `getPaletteFromClustering` or `quantizeWithClustering` to get any number of palettes without clustering again.
|
|
165
|
+
|
|
166
|
+
### `getPaletteFromClustering(clustering, k): Promise<Uint8Array>`
|
|
167
|
+
Cuts a clustering to at most `k` colours, returned as flat RGB bytes. This takes well under a millisecond. Colours come in split order: index 0 is the dominant colour, and the palette for `k + 1` is the palette for `k` with one entry refined (the larger half of a split keeps its parent's place) and the smaller half appended. Accepts clusterings from 1.x too.
|
|
168
|
+
|
|
169
|
+
### `getPalette(image, k, options?): Promise<Uint8Array>`
|
|
170
|
+
`getClustering` followed by `getPaletteFromClustering`. Options: `colorSpace`, `precision`, `alpha`.
|
|
171
|
+
|
|
172
|
+
### `quantize(image, k, options?): Promise<Uint8Array | ImageData | RawImage>`
|
|
173
|
+
Reduces the image to at most `k` colours. Options: `colorSpace`, `precision`, `alpha`, `dither`, `width`.
|
|
174
|
+
|
|
175
|
+
### `quantizeWithClustering(image, clustering, k, options?)`
|
|
176
|
+
Quantizes using a clustering you already have. Options: `colorSpace` (defaults to the clustering's), `dither`, `width`.
|
|
177
|
+
|
|
178
|
+
### `quantizeWithPalette(image, palette, options?)`
|
|
179
|
+
Maps each pixel to its nearest colour in any palette (flat RGB bytes). The result doesn't depend on the palette's order: equally near colours are decided by their RGB value. Options: `colorSpace`, `dither`, `width`.
|
|
180
|
+
|
|
103
181
|
### `init(): Promise<void>`
|
|
104
|
-
|
|
182
|
+
Loads the WebAssembly module. Every other function does this on first use, so calling it is optional, for example to warm up before a batch.
|
|
105
183
|
|
|
106
|
-
|
|
107
|
-
Computes a compact hierarchical clustering from the image's color histogram. The result can be passed to `getPaletteFromClustering` or `quantizeWithClustering` to avoid redundant work.
|
|
184
|
+
Invalid inputs, palette sizes and options (including unknown option names) are rejected with a descriptive error.
|
|
108
185
|
|
|
109
|
-
|
|
110
|
-
Returns a palette of up to `k` colors as a flat RGB byte array (`k * 3` bytes).
|
|
186
|
+
## Migrating from 1.x
|
|
111
187
|
|
|
112
|
-
|
|
113
|
-
|
|
188
|
+
2.0 keeps the same functions and defaults (`rgb`, no dithering, exact `precision`). What changes:
|
|
189
|
+
|
|
190
|
+
- **Palette order.** Palettes come in split order, dominant colour first, rather than in an arbitrary order. For opaque images they contain exactly the same colours as 1.2.
|
|
191
|
+
- **Transparency.** RGBA pixels are weighted by opacity, so palettes of images with transparency change: fully transparent pixels no longer contribute. Pass `{ alpha: 'ignore' }` for the 1.x behaviour.
|
|
192
|
+
- **Clustering bytes.** Clusterings gain a 4-byte header recording their colour space and precision. Clusterings saved by 1.x still load. Anything that inspected the raw bytes needs to skip the header.
|
|
193
|
+
- **`quantizeWithClustering`** matches in the clustering's colour space unless you pass `colorSpace`.
|
|
194
|
+
- **Exact ties** in pixel mapping go to the colour with the smaller RGB value, so results don't depend on palette order. A small number of pixels that sit exactly between two palette colours may map differently from 1.2.
|
|
195
|
+
- **Invalid clusterings** passed to `getPaletteFromClustering` or `quantizeWithClustering` now throw instead of giving an empty palette.
|
|
196
|
+
|
|
197
|
+
## Demo
|
|
198
|
+
|
|
199
|
+
```sh
|
|
200
|
+
git clone https://github.com/RohanFredriksson/agglomerative-clustering && cd agglomerative-clustering
|
|
201
|
+
npm install && npm run build # building needs Emscripten (em++) on your PATH
|
|
202
|
+
npm run demo # then open http://localhost:8080/demo/
|
|
203
|
+
```
|
|
204
|
+
|
|
205
|
+
The demo clusters an image once, then re-cuts and re-maps it live as you drag the palette-size and dithering sliders. You can switch colour space and precision, and drop in your own images.
|
|
206
|
+
|
|
207
|
+
## How it works
|
|
208
|
+
|
|
209
|
+
1. **Histogram.** Distinct colours are counted with an open-addressing hash table. With `precision` below 8, colours are first grouped by their top bits.
|
|
210
|
+
2. **Exact Ward clustering.** A nearest-neighbour chain finds mutually cheapest pairs and merges them. Ward's criterion is reducible, so this produces exactly the same hierarchy as repeatedly merging the globally cheapest pair, without a priority queue.
|
|
211
|
+
3. **Fast partner search.** Clusters live in an adaptive 3D grid sized to the occupied part of colour space, with per-column occupancy bits so searches step over empty cells. Searches prune whole cells using each cell's colour box and lightest member, compute four Ward costs at once with WASM SIMD, and skip most candidates with a division-free float test before the exact double-precision check. Clusters whose searches are expensive cache their best candidates.
|
|
212
|
+
4. **Compact output.** The hierarchy is stored as a 4-byte header and 9-byte merge records in reverse order, each listing its heavier half first. Cutting to `k` colours replays the first `k − 1` records, which gives the stable split order.
|
|
213
|
+
5. **Mapping.** A memo of recent colours, then a grid over colour space whose cells list the palette entries that can be nearest there (a KD-tree for palettes above 256 colours), maps pixels to the palette, with optional error-diffusion dithering.
|
|
114
214
|
|
|
115
|
-
|
|
116
|
-
Quantizes the image to at most `k` colors. Return type matches the input type.
|
|
215
|
+
The algorithm is C++17 compiled to WebAssembly with Emscripten. Architecture notes for contributors are in [CLAUDE.md](CLAUDE.md).
|
|
117
216
|
|
|
118
|
-
|
|
119
|
-
Quantizes using a precomputed clustering. Return type matches the input type.
|
|
217
|
+
## License
|
|
120
218
|
|
|
121
|
-
|
|
122
|
-
Quantizes using an already-computed palette. Return type matches the input type.
|
|
219
|
+
MIT © Rohan Fredriksson
|
package/dist/clustering.js
CHANGED
|
@@ -1,2 +1,14 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
var createWasmModule = (() => {
|
|
2
|
+
|
|
3
|
+
return (
|
|
4
|
+
async function(moduleArg = {}) {
|
|
5
|
+
var moduleRtn;
|
|
6
|
+
|
|
7
|
+
var Module=moduleArg;var ENVIRONMENT_IS_WEB=typeof window=="object";var ENVIRONMENT_IS_WORKER=typeof WorkerGlobalScope!="undefined";var ENVIRONMENT_IS_NODE=typeof process=="object"&&process.versions?.node&&process.type!="renderer";if(ENVIRONMENT_IS_NODE){const{createRequire}=await import("module");var require=createRequire(import.meta.url)}var arguments_=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var _scriptName=import.meta.url;var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("fs");if(_scriptName.startsWith("file:")){scriptDirectory=require("path").dirname(require("url").fileURLToPath(_scriptName))+"/"}readBinary=filename=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename);return ret};readAsync=async(filename,binary=true)=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename,binary?undefined:"utf8");return ret};if(process.argv.length>1){thisProgram=process.argv[1].replace(/\\/g,"/")}arguments_=process.argv.slice(2);quit_=(status,toThrow)=>{process.exitCode=status;throw toThrow}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}{if(ENVIRONMENT_IS_WORKER){readBinary=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=async url=>{if(isFileURI(url)){return new Promise((resolve,reject)=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=()=>{if(xhr.status==200||xhr.status==0&&xhr.response){resolve(xhr.response);return}reject(xhr.status)};xhr.onerror=reject;xhr.send(null)})}var response=await fetch(url,{credentials:"same-origin"});if(response.ok){return response.arrayBuffer()}throw new Error(response.status+" : "+response.url)}}}else{}var out=console.log.bind(console);var err=console.error.bind(console);var wasmBinary;var ABORT=false;var isFileURI=filename=>filename.startsWith("file://");var readyPromiseResolve,readyPromiseReject;var wasmMemory;var HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64;var HEAP64,HEAPU64;var runtimeInitialized=false;function updateMemoryViews(){var b=wasmMemory.buffer;HEAP8=new Int8Array(b);HEAP16=new Int16Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);HEAPU16=new Uint16Array(b);HEAP32=new Int32Array(b);HEAPU32=new Uint32Array(b);HEAPF32=new Float32Array(b);HEAPF64=new Float64Array(b);HEAP64=new BigInt64Array(b);HEAPU64=new BigUint64Array(b)}function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(onPreRuns)}function initRuntime(){runtimeInitialized=true;wasmExports["e"]()}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(onPostRuns)}var runDependencies=0;var dependenciesFulfilled=null;function addRunDependency(id){runDependencies++;Module["monitorRunDependencies"]?.(runDependencies)}function removeRunDependency(id){runDependencies--;Module["monitorRunDependencies"]?.(runDependencies);if(runDependencies==0){if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}}function abort(what){Module["onAbort"]?.(what);what="Aborted("+what+")";err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);readyPromiseReject?.(e);throw e}var wasmBinaryFile;function findWasmBinary(){if(Module["locateFile"]){return locateFile("clustering.wasm")}return new URL("clustering.wasm",import.meta.url).href}function getBinarySync(file){if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(binaryFile){if(!wasmBinary){try{var response=await readAsync(binaryFile);return new Uint8Array(response)}catch{}}return getBinarySync(binaryFile)}async function instantiateArrayBuffer(binaryFile,imports){try{var binary=await getWasmBinary(binaryFile);var instance=await WebAssembly.instantiate(binary,imports);return instance}catch(reason){err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)}}async function instantiateAsync(binary,binaryFile,imports){if(!binary&&typeof WebAssembly.instantiateStreaming=="function"&&!isFileURI(binaryFile)&&!ENVIRONMENT_IS_NODE){try{var response=fetch(binaryFile,{credentials:"same-origin"});var instantiationResult=await WebAssembly.instantiateStreaming(response,imports);return instantiationResult}catch(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation")}}return instantiateArrayBuffer(binaryFile,imports)}function getWasmImports(){return{a:wasmImports}}async function createWasm(){function receiveInstance(instance,module){wasmExports=instance.exports;wasmMemory=wasmExports["d"];updateMemoryViews();assignWasmExports(wasmExports);removeRunDependency("wasm-instantiate");return wasmExports}addRunDependency("wasm-instantiate");function receiveInstantiationResult(result){return receiveInstance(result["instance"])}var info=getWasmImports();if(Module["instantiateWasm"]){return new Promise((resolve,reject)=>{Module["instantiateWasm"](info,(mod,inst)=>{resolve(receiveInstance(mod,inst))})})}wasmBinaryFile??=findWasmBinary();var result=await instantiateAsync(wasmBinary,wasmBinaryFile,info);var exports=receiveInstantiationResult(result);return exports}class ExitStatus{name="ExitStatus";constructor(status){this.message=`Program terminated with exit(${status})`;this.status=status}}var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};var onPostRuns=[];var addOnPostRun=cb=>onPostRuns.push(cb);var onPreRuns=[];var addOnPreRun=cb=>onPreRuns.push(cb);var noExitRuntime=true;class ExceptionInfo{constructor(excPtr){this.excPtr=excPtr;this.ptr=excPtr-24}set_type(type){HEAPU32[this.ptr+4>>2]=type}get_type(){return HEAPU32[this.ptr+4>>2]}set_destructor(destructor){HEAPU32[this.ptr+8>>2]=destructor}get_destructor(){return HEAPU32[this.ptr+8>>2]}set_caught(caught){caught=caught?1:0;HEAP8[this.ptr+12]=caught}get_caught(){return HEAP8[this.ptr+12]!=0}set_rethrown(rethrown){rethrown=rethrown?1:0;HEAP8[this.ptr+13]=rethrown}get_rethrown(){return HEAP8[this.ptr+13]!=0}init(type,destructor){this.set_adjusted_ptr(0);this.set_type(type);this.set_destructor(destructor)}set_adjusted_ptr(adjustedPtr){HEAPU32[this.ptr+16>>2]=adjustedPtr}get_adjusted_ptr(){return HEAPU32[this.ptr+16>>2]}}var exceptionLast=0;var uncaughtExceptionCount=0;var ___cxa_throw=(ptr,type,destructor)=>{var info=new ExceptionInfo(ptr);info.init(type,destructor);exceptionLast=ptr;uncaughtExceptionCount++;throw exceptionLast};var __abort_js=()=>abort("");var getHeapMax=()=>2147483648;var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var growMemory=size=>{var b=wasmMemory.buffer;var pages=(size-b.byteLength+65535)/65536|0;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){}};var _emscripten_resize_heap=requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignMemory(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement){return true}}return false};{if(Module["noExitRuntime"])noExitRuntime=Module["noExitRuntime"];if(Module["print"])out=Module["print"];if(Module["printErr"])err=Module["printErr"];if(Module["wasmBinary"])wasmBinary=Module["wasmBinary"];if(Module["arguments"])arguments_=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"]}var _malloc,_get_clustering,_get_palette,_get_palette_from_clustering,_quantize,_quantize_with_clustering,_quantize_with_palette,_free;function assignWasmExports(wasmExports){Module["_malloc"]=_malloc=wasmExports["f"];Module["_get_clustering"]=_get_clustering=wasmExports["g"];Module["_get_palette"]=_get_palette=wasmExports["h"];Module["_get_palette_from_clustering"]=_get_palette_from_clustering=wasmExports["i"];Module["_quantize"]=_quantize=wasmExports["j"];Module["_quantize_with_clustering"]=_quantize_with_clustering=wasmExports["k"];Module["_quantize_with_palette"]=_quantize_with_palette=wasmExports["l"];Module["_free"]=_free=wasmExports["m"]}var wasmImports={a:___cxa_throw,b:__abort_js,c:_emscripten_resize_heap};var wasmExports=await createWasm();function run(){if(runDependencies>0){dependenciesFulfilled=run;return}preRun();if(runDependencies>0){dependenciesFulfilled=run;return}function doRun(){Module["calledRun"]=true;if(ABORT)return;initRuntime();readyPromiseResolve?.(Module);Module["onRuntimeInitialized"]?.();postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(()=>{setTimeout(()=>Module["setStatus"](""),1);doRun()},1)}else{doRun()}}function preInit(){if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].shift()()}}}preInit();run();if(runtimeInitialized){moduleRtn=Module}else{moduleRtn=new Promise((resolve,reject)=>{readyPromiseResolve=resolve;readyPromiseReject=reject})}
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
return moduleRtn;
|
|
11
|
+
}
|
|
12
|
+
);
|
|
13
|
+
})();
|
|
14
|
+
export default createWasmModule;
|
package/dist/clustering.wasm
CHANGED
|
Binary file
|