gb-image-decoder 1.3.1 → 2.0.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/dist/index.cjs CHANGED
@@ -1,5 +1,7 @@
1
1
  'use strict';
2
2
 
3
+ const ohash = require('ohash');
4
+
3
5
  var BlendMode = /* @__PURE__ */ ((BlendMode2) => {
4
6
  BlendMode2["NORMAL"] = "normal";
5
7
  BlendMode2["NORMAL_S"] = "normal_s";
@@ -59,19 +61,17 @@ const TILE_PIXEL_WIDTH = 8;
59
61
  const TILE_PIXEL_HEIGHT = 8;
60
62
  const TILES_PER_LINE = 20;
61
63
  const TILES_PER_COLUMN = 18;
62
- const FRAME_SIZE = 2;
63
- const FRAME_TILES = FRAME_SIZE * 2;
64
- const DEFAULT_FULL_PIXEL_HEIGHT = TILES_PER_COLUMN * TILE_PIXEL_HEIGHT;
65
- const DEFAULT_FULL_PIXEL_WIDTH = TILES_PER_LINE * TILE_PIXEL_WIDTH;
64
+ const FRAME_WIDTH = 2;
66
65
  const BW_PALETTE = [16777215, 11184810, 5592405, 0];
67
66
  const BW_PALETTE_HEX = ["#ffffff", "#aaaaaa", "#555555", "#000000"];
68
67
  const BLACK_LINE = Array(TILES_PER_LINE).fill(BLACK);
69
68
  const WHITE_LINE = Array(TILES_PER_LINE).fill(WHITE);
70
- const defaultPalette = {
71
- r: [0, 84, 172, 255],
72
- g: [0, 84, 172, 255],
73
- b: [0, 84, 172, 255],
74
- n: [0, 85, 170, 255],
69
+ const RGBN_SHADES = [0, 85, 170, 255];
70
+ const defaultRGBNPalette = {
71
+ r: RGBN_SHADES,
72
+ g: RGBN_SHADES,
73
+ b: RGBN_SHADES,
74
+ n: RGBN_SHADES,
75
75
  blend: BlendMode.MULTIPLY
76
76
  };
77
77
 
@@ -108,18 +108,17 @@ const decodeTile = (rawBytes = BLACK) => {
108
108
  return pixels;
109
109
  };
110
110
 
111
- const tileIndexIsPartOfFrame = (tileIndex, imageStartLine, handleExportFrame = ExportFrameMode.FRAMEMODE_KEEP) => {
111
+ const tileIndexIsPartOfFrame = (tileIndex, imageStartLine, handleExportFrame) => {
112
112
  if (handleExportFrame === ExportFrameMode.FRAMEMODE_CROP) {
113
113
  return false;
114
114
  }
115
- const checkIndex = tileIndex - (handleExportFrame === ExportFrameMode.FRAMEMODE_KEEP ? 0 : 20);
116
- if (checkIndex < imageStartLine * 20) {
115
+ if (tileIndex < imageStartLine * 20) {
117
116
  return true;
118
117
  }
119
- if (checkIndex >= imageStartLine * 20 + 280) {
118
+ if (tileIndex >= imageStartLine * 20 + 280) {
120
119
  return true;
121
120
  }
122
- switch (checkIndex % 20) {
121
+ switch (tileIndex % 20) {
123
122
  case 0:
124
123
  case 1:
125
124
  case 18:
@@ -130,29 +129,18 @@ const tileIndexIsPartOfFrame = (tileIndex, imageStartLine, handleExportFrame = E
130
129
  }
131
130
  };
132
131
 
133
- const calculateImageStartLine = (handleExportFrame, imageStartLine) => {
134
- switch (handleExportFrame) {
135
- case ExportFrameMode.FRAMEMODE_CROP:
136
- return 0;
137
- case ExportFrameMode.FRAMEMODE_SQUARE_WHITE:
138
- case ExportFrameMode.FRAMEMODE_SQUARE_BLACK:
139
- return 2;
140
- case ExportFrameMode.FRAMEMODE_KEEP:
141
- default:
142
- return imageStartLine;
143
- }
144
- };
145
132
  const getRGBValue = ({
146
133
  pixels,
147
134
  index,
148
135
  tileIndex,
149
- imageStartLine,
150
- handleExportFrame,
151
- colorData,
152
- frameColorData
136
+ imageContext: {
137
+ imageStartLine,
138
+ handleExportFrame,
139
+ imagePalette,
140
+ framePalette
141
+ }
153
142
  }) => {
154
- const calculatedImageStartLine = calculateImageStartLine(handleExportFrame, imageStartLine);
155
- const palette = tileIndexIsPartOfFrame(tileIndex, calculatedImageStartLine, handleExportFrame) ? frameColorData : colorData;
143
+ const palette = tileIndexIsPartOfFrame(tileIndex, imageStartLine, handleExportFrame) ? framePalette : imagePalette;
156
144
  const value = palette[pixels[index]];
157
145
  return {
158
146
  // eslint-disable-next-line no-bitwise
@@ -164,505 +152,406 @@ const getRGBValue = ({
164
152
  };
165
153
  };
166
154
 
167
- const createCanvasElement = () => {
168
- try {
169
- return document.createElement("canvas");
170
- } catch (error) {
171
- throw new Error("cannot create canvas element");
172
- }
173
- };
174
- const createImageData = (rawImageData, width, height) => new ImageData(rawImageData, width, height);
175
-
176
- var __defProp$1 = Object.defineProperty;
177
- var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
178
- var __publicField$1 = (obj, key, value) => {
179
- __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
180
- return value;
181
- };
182
- class Decoder {
183
- constructor(options) {
184
- __publicField$1(this, "canvas");
185
- __publicField$1(this, "tiles");
186
- __publicField$1(this, "colors");
187
- __publicField$1(this, "frameColors");
188
- __publicField$1(this, "rawImageData");
189
- __publicField$1(this, "lockFrame");
190
- __publicField$1(this, "colorData");
191
- __publicField$1(this, "frameColorData");
192
- __publicField$1(this, "tilesPerLine");
193
- __publicField$1(this, "imageStartLine");
194
- __publicField$1(this, "canvasCreator");
195
- __publicField$1(this, "imageDataCreator");
196
- this.canvas = null;
197
- this.tiles = [];
198
- this.colors = [];
199
- this.frameColors = [];
200
- this.rawImageData = null;
201
- this.lockFrame = false;
202
- this.colorData = [...BW_PALETTE];
203
- this.frameColorData = [...BW_PALETTE];
204
- this.tilesPerLine = options?.tilesPerLine || TILES_PER_LINE;
205
- this.imageStartLine = 2;
206
- this.canvasCreator = options?.canvasCreator || createCanvasElement;
207
- this.imageDataCreator = options?.imageDataCreator || createImageData;
208
- }
209
- update({
210
- canvas,
211
- tiles,
212
- palette,
213
- framePalette,
214
- imageStartLine = 2
215
- }) {
216
- const startLineChanged = this.setImageStartLine(imageStartLine);
217
- const canvasChanged = canvas ? this.setCanvas(canvas) : false;
218
- const usedFramePalette = this.tilesPerLine === TILES_PER_LINE ? framePalette : palette;
219
- const palettesChanged = this.setPalettes(palette, usedFramePalette);
220
- if (startLineChanged || canvasChanged || palettesChanged || !this.tiles.length) {
221
- this.tiles = [];
222
- }
223
- const tilesChanged = this.setTiles(tiles);
224
- const newHeight = this.getHeight();
225
- const newWidth = this.getWidth();
226
- if (!this.canvas) {
227
- return;
228
- }
229
- if (newHeight === 0) {
230
- this.canvas.height = 0;
231
- return;
155
+ class UrlCache {
156
+ static rendered = {};
157
+ static rendering = {};
158
+ async getUrl(hash) {
159
+ if (UrlCache.rendered.hasOwnProperty(hash)) {
160
+ return UrlCache.rendered[hash];
232
161
  }
233
- if (this.canvas.height !== newHeight || this.canvas.width !== newWidth || !this.rawImageData?.length) {
234
- this.canvas.height = newHeight;
235
- this.canvas.width = newWidth;
236
- const newRawImageData = new Uint8ClampedArray(newWidth * newHeight * 4);
237
- this.rawImageData?.forEach((value, index) => {
238
- newRawImageData[index] = value;
239
- });
240
- this.rawImageData = newRawImageData;
162
+ if (UrlCache.rendering.hasOwnProperty(hash)) {
163
+ const url = await UrlCache.rendering[hash];
164
+ return url;
241
165
  }
242
- tilesChanged.forEach(({ index, newTile }) => {
243
- this.renderTile(index, newTile);
244
- });
245
- this.updateCanvas(newWidth, newHeight);
166
+ return null;
246
167
  }
247
- setImageStartLine(imageStartLine) {
248
- if (this.imageStartLine === imageStartLine) {
249
- return false;
168
+ async setUrl(hash, promise) {
169
+ if (UrlCache.rendered.hasOwnProperty(hash) || UrlCache.rendering.hasOwnProperty(hash)) {
170
+ console.warn("hash already exists!");
250
171
  }
251
- this.imageStartLine = imageStartLine;
252
- return true;
172
+ UrlCache.rendering[hash] = promise;
173
+ UrlCache.rendered[hash] = await promise;
174
+ delete UrlCache.rendering[hash];
253
175
  }
254
- updateCanvas(newWidth, newHeight) {
255
- if (!this.canvas || !this.rawImageData?.length) {
176
+ }
177
+
178
+ const toObjectUrl = async (canvas) => new Promise((resolve, reject) => {
179
+ canvas.toBlob((blob) => {
180
+ if (!blob) {
181
+ reject(new Error("Could not generate Blob from canvas"));
256
182
  return;
257
183
  }
258
- const context = this.canvas.getContext("2d");
259
- const imageData = this.imageDataCreator(this.rawImageData, newWidth, newHeight);
260
- context?.putImageData(imageData, 0, 0);
261
- }
262
- getScaledCanvas(scaleFactor, handleExportFrame = ExportFrameMode.FRAMEMODE_KEEP) {
263
- let handleFrameMode = handleExportFrame;
264
- if (this.tilesPerLine !== TILES_PER_LINE && handleFrameMode !== ExportFrameMode.FRAMEMODE_KEEP) {
265
- handleFrameMode = ExportFrameMode.FRAMEMODE_KEEP;
184
+ try {
185
+ resolve(URL.createObjectURL(blob));
186
+ } catch (error) {
187
+ reject(error);
266
188
  }
267
- const {
268
- initialHeight,
269
- initialWidth,
270
- tilesPerLine
271
- } = this.getScaledCanvasSize(handleFrameMode);
272
- const canvas = this.canvasCreator();
189
+ });
190
+ });
191
+ const dataUrlFromRawOutput = async ({
192
+ data,
193
+ dimensions: { width, height }
194
+ }, scaleFactor, hash, canvasCreator) => {
195
+ const urlCache = new UrlCache();
196
+ urlCache.setUrl(hash, new Promise((resolve) => {
197
+ const canvas = canvasCreator();
198
+ canvas.width = width * scaleFactor;
199
+ canvas.height = height * scaleFactor;
273
200
  const context = canvas.getContext("2d");
274
- if (!context) {
275
- throw new Error("no canvas context");
276
- }
277
- canvas.width = initialWidth * scaleFactor;
278
- canvas.height = initialHeight * scaleFactor;
279
- this.getExportTiles(handleFrameMode).forEach((tile, index) => {
280
- this.paintTileScaled(decodeTile(tile), index, context, scaleFactor, tilesPerLine, handleFrameMode);
281
- });
282
- return canvas;
283
- }
284
- getScaledCanvasSize(handleExportFrame) {
285
- const width = this.getWidth();
286
- const height = this.getHeight();
287
- switch (handleExportFrame) {
288
- case ExportFrameMode.FRAMEMODE_KEEP:
289
- return {
290
- initialHeight: height,
291
- initialWidth: width,
292
- tilesPerLine: this.tilesPerLine
293
- };
294
- case ExportFrameMode.FRAMEMODE_CROP:
295
- return {
296
- initialHeight: DEFAULT_FULL_PIXEL_HEIGHT - TILE_PIXEL_HEIGHT * FRAME_TILES,
297
- initialWidth: DEFAULT_FULL_PIXEL_WIDTH - TILE_PIXEL_WIDTH * FRAME_TILES,
298
- tilesPerLine: TILES_PER_LINE - FRAME_TILES
299
- };
300
- case ExportFrameMode.FRAMEMODE_SQUARE_BLACK:
301
- case ExportFrameMode.FRAMEMODE_SQUARE_WHITE:
302
- return {
303
- initialHeight: width,
304
- initialWidth: width,
305
- tilesPerLine: this.tilesPerLine
306
- };
307
- default:
308
- throw new Error(`unknown export mode ${handleExportFrame}`);
309
- }
310
- }
311
- getExportTiles(handleExportFrame) {
312
- if (!this.tiles) {
313
- throw new Error("no tiles to export");
314
- }
315
- switch (handleExportFrame) {
316
- case ExportFrameMode.FRAMEMODE_KEEP:
317
- return this.tiles;
318
- case ExportFrameMode.FRAMEMODE_CROP:
319
- return this.getCroppedTiles();
320
- case ExportFrameMode.FRAMEMODE_SQUARE_BLACK:
321
- return [
322
- ...BLACK_LINE,
323
- ...this.getDefaultImageRange(),
324
- ...BLACK_LINE
325
- ];
326
- case ExportFrameMode.FRAMEMODE_SQUARE_WHITE:
327
- return [
328
- ...WHITE_LINE,
329
- ...this.getDefaultImageRange(),
330
- ...WHITE_LINE
331
- ];
332
- default:
333
- throw new Error(`unknown export mode ${handleExportFrame}`);
334
- }
335
- }
336
- getCroppedTiles() {
337
- return this.tiles.reduce((acc, tile, index) => tileIndexIsPartOfFrame(index, this.imageStartLine, ExportFrameMode.FRAMEMODE_KEEP) ? acc : [...acc, tile], []);
338
- }
339
- // for wild frame image, this returns the part of theimage
340
- // which has the image data in the default position by cropping
341
- // away part of the wild frame which does not fit into 160x144
342
- getDefaultImageRange() {
343
- const wholeImageStartLine = this.imageStartLine - FRAME_SIZE;
344
- const startIndex = wholeImageStartLine * TILES_PER_LINE;
345
- return this.tiles.slice(startIndex, startIndex + TILES_PER_LINE * TILES_PER_COLUMN);
346
- }
347
- setCanvas(canvas) {
348
- if (this.canvas === canvas) {
349
- return false;
350
- }
351
- this.canvas = canvas;
352
- return true;
201
+ const imageData = new ImageData(data, canvas.width, canvas.height);
202
+ context?.putImageData(imageData, 0, 0);
203
+ resolve(toObjectUrl(canvas));
204
+ }));
205
+ const url = await urlCache.getUrl(hash);
206
+ if (!url) {
207
+ throw new Error("error generating image");
353
208
  }
354
- setPalettes(palette, framePalette) {
355
- if (this.colors[0] === palette[0] && this.colors[1] === palette[1] && this.colors[2] === palette[2] && this.colors[3] === palette[3] && this.frameColors[0] === framePalette[0] && this.frameColors[1] === framePalette[1] && this.frameColors[2] === framePalette[2] && this.frameColors[3] === framePalette[3]) {
356
- return false;
357
- }
358
- this.colors = palette;
359
- this.frameColors = framePalette;
360
- this.colors.forEach((color, index) => {
361
- this.colorData[index] = color.length !== 7 ? BW_PALETTE[index] : parseInt(color.substring(1), 16);
362
- });
363
- this.frameColors.forEach((color, index) => {
364
- this.frameColorData[index] = color.length !== 7 ? BW_PALETTE[index] : parseInt(color.substring(1), 16);
365
- });
366
- return true;
209
+ return url;
210
+ };
211
+
212
+ const createCanvasElement = () => {
213
+ try {
214
+ return document.createElement("canvas");
215
+ } catch (error) {
216
+ throw new Error("cannot create canvas element");
367
217
  }
368
- setTiles(tiles) {
369
- const changedTiles = tiles.reduce((acc, newTile, index) => {
370
- const changed = newTile !== this.tiles[index];
371
- if (!changed) {
372
- return acc;
373
- }
374
- return [
375
- ...acc,
376
- {
377
- index,
378
- newTile
379
- }
380
- ];
381
- }, []);
382
- this.tiles = tiles;
383
- return changedTiles;
218
+ };
219
+
220
+ const padLines = {
221
+ [ExportFrameMode.FRAMEMODE_SQUARE_BLACK]: BLACK_LINE,
222
+ [ExportFrameMode.FRAMEMODE_SQUARE_WHITE]: WHITE_LINE
223
+ };
224
+ const getPalettes = (imagePalette, framePalette, tilesPerLine) => {
225
+ if (tilesPerLine !== TILES_PER_LINE) {
226
+ return {
227
+ imagePalette,
228
+ framePalette: imagePalette
229
+ };
384
230
  }
385
- renderTile(tileIndex, rawLine) {
386
- if (rawLine === SKIP_LINE) {
387
- this.paintTile(null, tileIndex);
388
- } else {
389
- const tile = decodeTile(rawLine);
390
- this.paintTile(tile, tileIndex);
231
+ return {
232
+ imagePalette,
233
+ framePalette
234
+ };
235
+ };
236
+ const getDimensions$1 = (tilesLength, tilesPerLine) => ({
237
+ width: TILE_PIXEL_WIDTH * tilesPerLine,
238
+ height: TILE_PIXEL_HEIGHT * Math.ceil(tilesLength / tilesPerLine)
239
+ });
240
+ const getCroppedTiles = (tiles, imageContext) => ({
241
+ tiles: tiles.reduce((acc, tile, index) => tileIndexIsPartOfFrame(index, imageContext.imageStartLine, ExportFrameMode.FRAMEMODE_KEEP) ? acc : [...acc, tile], []),
242
+ dimensions: { width: 128, height: 112 },
243
+ contextUpdates: { tilesPerLine: 16, imageStartLine: 0 }
244
+ });
245
+ const getPaddedSquare = (tiles, padLine, imageContext) => {
246
+ let wholeImageStartLine = imageContext.imageStartLine - FRAME_WIDTH - 1;
247
+ const paddedTiles = [...tiles];
248
+ const square20by20tiles = TILES_PER_LINE ** 2;
249
+ while (paddedTiles.length < square20by20tiles || wholeImageStartLine < 0) {
250
+ paddedTiles.unshift(...padLine);
251
+ paddedTiles.push(...padLine);
252
+ wholeImageStartLine += 1;
253
+ }
254
+ const startIndex = wholeImageStartLine * TILES_PER_LINE;
255
+ return {
256
+ tiles: paddedTiles.slice(startIndex, startIndex + square20by20tiles),
257
+ dimensions: { width: 160, height: 160 },
258
+ contextUpdates: { tilesPerLine: 20, imageStartLine: 3 }
259
+ };
260
+ };
261
+ const applyCrop = (tiles, imageContext) => {
262
+ const checkFrameMode = imageContext.tilesPerLine !== TILES_PER_LINE ? ExportFrameMode.FRAMEMODE_KEEP : imageContext.handleExportFrame;
263
+ switch (checkFrameMode) {
264
+ case ExportFrameMode.FRAMEMODE_KEEP: {
265
+ return {
266
+ tiles,
267
+ dimensions: getDimensions$1(tiles.length, imageContext.tilesPerLine),
268
+ contextUpdates: {}
269
+ };
391
270
  }
392
- }
393
- // This paints the tile with a specified offset and pixel width
394
- paintTile(pixels, index) {
395
- if (!this.rawImageData) {
396
- return;
271
+ case ExportFrameMode.FRAMEMODE_CROP: {
272
+ return getCroppedTiles(tiles, imageContext);
397
273
  }
398
- const tileXOffset = index % this.tilesPerLine;
399
- const tileYOffset = Math.floor(index / this.tilesPerLine);
400
- const pixelXOffset = TILE_PIXEL_WIDTH * tileXOffset;
401
- const pixelYOffset = TILE_PIXEL_HEIGHT * tileYOffset;
402
- for (let x = 0; x < TILE_PIXEL_WIDTH; x += 1) {
403
- for (let y = 0; y < TILE_PIXEL_HEIGHT; y += 1) {
404
- const rawIndex = (pixelXOffset + x + (pixelYOffset + y) * this.tilesPerLine * TILE_PIXEL_WIDTH) * 4;
405
- if (pixels !== null) {
406
- const color = getRGBValue({
407
- pixels,
408
- index: y * TILE_PIXEL_WIDTH + x,
409
- tileIndex: index,
410
- imageStartLine: this.imageStartLine,
411
- handleExportFrame: ExportFrameMode.FRAMEMODE_KEEP,
412
- colorData: this.colorData,
413
- frameColorData: this.frameColorData
414
- });
415
- this.rawImageData[rawIndex] = color.r;
416
- this.rawImageData[rawIndex + 1] = color.g;
417
- this.rawImageData[rawIndex + 2] = color.b;
418
- this.rawImageData[rawIndex + 3] = 255;
419
- } else {
420
- this.rawImageData[rawIndex] = 0;
421
- this.rawImageData[rawIndex + 1] = 0;
422
- this.rawImageData[rawIndex + 2] = 0;
423
- this.rawImageData[rawIndex + 3] = 0;
424
- }
425
- }
274
+ case ExportFrameMode.FRAMEMODE_SQUARE_BLACK:
275
+ case ExportFrameMode.FRAMEMODE_SQUARE_WHITE: {
276
+ const padLine = padLines[checkFrameMode];
277
+ return getPaddedSquare(tiles, padLine, imageContext);
426
278
  }
279
+ default:
280
+ throw new Error(`unknown export mode ${imageContext.handleExportFrame}`);
427
281
  }
428
- paintTileScaled(pixels, index, canvasContext, pixelSize, tilesPerLine, handleExportFrame) {
429
- const tileXOffset = index % tilesPerLine;
430
- const tileYOffset = Math.floor(index / tilesPerLine);
431
- const pixelXOffset = TILE_PIXEL_WIDTH * tileXOffset * pixelSize;
432
- const pixelYOffset = TILE_PIXEL_HEIGHT * tileYOffset * pixelSize;
433
- for (let x = 0; x < TILE_PIXEL_WIDTH; x += 1) {
434
- for (let y = 0; y < TILE_PIXEL_HEIGHT; y += 1) {
282
+ };
283
+ const paintTile = (rawImageData, pixels, index, imageContext) => {
284
+ const tileXOffset = index % imageContext.tilesPerLine;
285
+ const tileYOffset = Math.floor(index / imageContext.tilesPerLine);
286
+ const pixelXOffset = TILE_PIXEL_WIDTH * tileXOffset;
287
+ const pixelYOffset = TILE_PIXEL_HEIGHT * tileYOffset;
288
+ for (let x = 0; x < TILE_PIXEL_WIDTH; x += 1) {
289
+ for (let y = 0; y < TILE_PIXEL_HEIGHT; y += 1) {
290
+ const rawIndex = (pixelXOffset + x + (pixelYOffset + y) * imageContext.tilesPerLine * TILE_PIXEL_WIDTH) * 4;
291
+ if (pixels !== null) {
435
292
  const color = getRGBValue({
436
293
  pixels,
437
294
  index: y * TILE_PIXEL_WIDTH + x,
438
295
  tileIndex: index,
439
- imageStartLine: this.imageStartLine,
440
- handleExportFrame,
441
- colorData: this.colorData,
442
- frameColorData: this.frameColorData
296
+ imageContext
443
297
  });
444
- canvasContext.fillStyle = `rgb(${color.r}, ${color.g}, ${color.b})`;
445
- canvasContext.fillRect(
446
- pixelXOffset + x * pixelSize,
447
- pixelYOffset + y * pixelSize,
448
- pixelSize + 1,
449
- pixelSize + 1
450
- );
298
+ rawImageData[rawIndex] = color.r;
299
+ rawImageData[rawIndex + 1] = color.g;
300
+ rawImageData[rawIndex + 2] = color.b;
301
+ rawImageData[rawIndex + 3] = 255;
302
+ } else {
303
+ rawImageData[rawIndex] = 0;
304
+ rawImageData[rawIndex + 1] = 0;
305
+ rawImageData[rawIndex + 2] = 0;
306
+ rawImageData[rawIndex + 3] = 0;
451
307
  }
452
308
  }
453
309
  }
454
- getHeight() {
455
- return TILE_PIXEL_HEIGHT * Math.ceil(this.tiles.length / this.tilesPerLine);
310
+ };
311
+ const renderTile = (rawImageData, rawLine, index, imageContext) => {
312
+ if (rawLine === SKIP_LINE) {
313
+ paintTile(rawImageData, null, index, imageContext);
314
+ } else {
315
+ const tile = decodeTile(rawLine);
316
+ paintTile(rawImageData, tile, index, imageContext);
456
317
  }
457
- getWidth() {
458
- return TILE_PIXEL_WIDTH * this.tilesPerLine;
318
+ };
319
+ const getFullParams$1 = (params) => ({
320
+ tiles: params.tiles,
321
+ imagePalette: params.imagePalette,
322
+ framePalette: params.framePalette || params.imagePalette,
323
+ imageStartLine: typeof params.imageStartLine === "number" ? params.imageStartLine : FRAME_WIDTH,
324
+ tilesPerLine: params.tilesPerLine || TILES_PER_LINE,
325
+ scaleFactor: params.scaleFactor || 1,
326
+ handleExportFrame: params.handleExportFrame || ExportFrameMode.FRAMEMODE_KEEP
327
+ });
328
+ const scaleRawImageData = (data, width, height, scale) => {
329
+ const newWidth = width * scale;
330
+ const newHeight = height * scale;
331
+ const scaled = new Uint8ClampedArray(newWidth * newHeight * 4);
332
+ for (let y = 0; y < height; y += 1) {
333
+ for (let x = 0; x < width; x += 1) {
334
+ const srcIndex = (y * width + x) * 4;
335
+ const r = data[srcIndex];
336
+ const g = data[srcIndex + 1];
337
+ const b = data[srcIndex + 2];
338
+ const a = data[srcIndex + 3];
339
+ for (let dy = 0; dy < scale; dy += 1) {
340
+ for (let dx = 0; dx < scale; dx += 1) {
341
+ const destX = x * scale + dx;
342
+ const destY = y * scale + dy;
343
+ const destIndex = (destY * newWidth + destX) * 4;
344
+ scaled[destIndex] = r;
345
+ scaled[destIndex + 1] = g;
346
+ scaled[destIndex + 2] = b;
347
+ scaled[destIndex + 3] = a;
348
+ }
349
+ }
350
+ }
459
351
  }
460
- }
461
-
462
- const hx2 = (n) => (n || 0).toString(16).padStart(2, "0");
463
- const paletteTemplates = {
464
- r: (v) => `#${hx2(v)}0000`,
465
- g: (v) => `#00${hx2(v)}00`,
466
- b: (v) => `#0000${hx2(v)}`,
467
- n: (v) => `#${hx2(v)}${hx2(v)}${hx2(v)}`
352
+ return {
353
+ data: scaled,
354
+ dimensions: {
355
+ width: newWidth,
356
+ height: newHeight
357
+ }
358
+ };
359
+ };
360
+ const getRawMonochromeImageData = (params) => {
361
+ const {
362
+ tiles,
363
+ imageStartLine,
364
+ imagePalette,
365
+ framePalette,
366
+ tilesPerLine,
367
+ handleExportFrame,
368
+ scaleFactor
369
+ } = params;
370
+ const imageContext = {
371
+ tilesPerLine,
372
+ imageStartLine,
373
+ handleExportFrame,
374
+ ...getPalettes(imagePalette, framePalette, tilesPerLine || TILES_PER_LINE)
375
+ };
376
+ const {
377
+ tiles: usedTiles,
378
+ dimensions: {
379
+ width,
380
+ height
381
+ },
382
+ contextUpdates
383
+ } = applyCrop(tiles, imageContext);
384
+ const updatedContext = {
385
+ ...imageContext,
386
+ ...contextUpdates
387
+ };
388
+ if (!height || !width) {
389
+ throw new Error("Image has no dimensions");
390
+ }
391
+ const rawImageData = new Uint8ClampedArray(width * height * 4);
392
+ usedTiles.forEach((newTile, index) => {
393
+ renderTile(rawImageData, newTile, index, updatedContext);
394
+ });
395
+ return scaleRawImageData(rawImageData, width, height, scaleFactor);
396
+ };
397
+ const getMonochromeImageUrl = async (params, canvasCreator = createCanvasElement) => {
398
+ const urlCache = new UrlCache();
399
+ const fullParams = getFullParams$1(params);
400
+ const hash = ohash.hash(fullParams);
401
+ const cachedUrl = await urlCache.getUrl(hash);
402
+ if (cachedUrl) {
403
+ return cachedUrl;
404
+ }
405
+ const rawOutput = getRawMonochromeImageData(fullParams);
406
+ return dataUrlFromRawOutput(rawOutput, fullParams.scaleFactor, hash, canvasCreator);
468
407
  };
469
408
 
470
- var __defProp = Object.defineProperty;
471
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
472
- var __publicField = (obj, key, value) => {
473
- __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
474
- return value;
409
+ const getFullParams = (params) => ({
410
+ tiles: params.tiles,
411
+ palette: params.palette,
412
+ lockFrame: params.lockFrame || false,
413
+ imageStartLine: typeof params.imageStartLine === "number" ? params.imageStartLine : FRAME_WIDTH,
414
+ tilesPerLine: params.tilesPerLine || TILES_PER_LINE,
415
+ scaleFactor: params.scaleFactor || 1,
416
+ handleExportFrame: params.handleExportFrame || ExportFrameMode.FRAMEMODE_KEEP
417
+ });
418
+ const singleChannelPalette = (palette, channelKey) => {
419
+ switch (channelKey) {
420
+ case ChannelKey.R:
421
+ return palette.map((shade) => (shade & 255) << 16).reverse();
422
+ case ChannelKey.G:
423
+ return palette.map((shade) => (shade & 255) << 8).reverse();
424
+ case ChannelKey.B:
425
+ return palette.map((shade) => shade & 255).reverse();
426
+ default:
427
+ return palette.map((shade) => {
428
+ const base = shade & 255;
429
+ return (base << 16) + (base << 8) + base;
430
+ }).reverse();
431
+ }
475
432
  };
476
- const createChannel = (key, decoderOptions) => {
477
- const canvas = decoderOptions.canvasCreator();
478
- const decoder = new Decoder(decoderOptions);
479
- decoder.update({
480
- framePalette: [],
481
- canvas,
482
- tiles: [],
483
- palette: []
433
+ const getDimensions = (canvases) => Object.values(canvases).reduce((acc, current) => {
434
+ if (current.width === 0 || current.height === 0) {
435
+ return acc;
436
+ }
437
+ return {
438
+ width: Math.max(current.width, acc.width),
439
+ height: Math.max(current.height, acc.height)
440
+ };
441
+ }, { width: 0, height: 0 });
442
+ const blendCanvases = (sourceCanvases, blendMode, canvasCreator) => {
443
+ const dimensions = getDimensions(sourceCanvases);
444
+ const targetCanvas = canvasCreator();
445
+ targetCanvas.width = dimensions.width;
446
+ targetCanvas.height = dimensions.height;
447
+ const targetContext = targetCanvas.getContext("2d");
448
+ channels.forEach((key) => {
449
+ const sourceCanvas = sourceCanvases[key];
450
+ if (sourceCanvas && sourceCanvas.width && sourceCanvas.height) {
451
+ if (key === ChannelKey.N) {
452
+ if (blendMode === BlendMode.NORMAL) {
453
+ return;
454
+ }
455
+ targetContext.globalCompositeOperation = blendModeNewName(blendMode);
456
+ } else {
457
+ targetContext.globalCompositeOperation = "lighter";
458
+ }
459
+ targetContext.drawImage(sourceCanvas, 0, 0);
460
+ }
484
461
  });
462
+ const imageData = targetContext.getImageData(0, 0, dimensions.width, dimensions.height);
485
463
  return {
486
- key,
487
- decoder,
488
- canvas
464
+ data: imageData.data,
465
+ dimensions: {
466
+ width: imageData.width,
467
+ height: imageData.height
468
+ }
489
469
  };
490
470
  };
491
- class RGBNDecoder {
492
- constructor(options) {
493
- __publicField(this, "canvas");
494
- __publicField(this, "palette");
495
- __publicField(this, "lockFrame");
496
- __publicField(this, "channels");
497
- __publicField(this, "tilesPerLine");
498
- __publicField(this, "canvasCreator");
499
- __publicField(this, "imageDataCreator");
500
- this.canvas = null;
501
- this.palette = defaultPalette;
502
- this.lockFrame = false;
503
- this.tilesPerLine = options?.tilesPerLine || TILES_PER_LINE;
504
- this.canvasCreator = options?.canvasCreator || createCanvasElement;
505
- this.imageDataCreator = options?.imageDataCreator || createImageData;
506
- const channelDecoderOptions = {
507
- tilesPerLine: this.tilesPerLine,
508
- canvasCreator: this.canvasCreator,
509
- imageDataCreator: this.imageDataCreator
510
- };
511
- this.channels = {
512
- r: createChannel(ChannelKey.R, channelDecoderOptions),
513
- g: createChannel(ChannelKey.G, channelDecoderOptions),
514
- b: createChannel(ChannelKey.B, channelDecoderOptions),
515
- n: createChannel(ChannelKey.N, channelDecoderOptions)
516
- };
517
- }
518
- update({
519
- canvas,
471
+ const getRawRGBNImageData = (params, canvasCreator) => {
472
+ const {
520
473
  tiles,
474
+ imageStartLine,
521
475
  palette,
522
- lockFrame = false
523
- }) {
524
- const canvasChanged = canvas ? this.setCanvas(canvas) : false;
525
- const paletteChanged = this.setPalette(palette);
526
- const lockFrameChanged = this.setLockFrame(lockFrame);
527
- const shouldUpdate = canvasChanged || paletteChanged || lockFrameChanged;
528
- const canvases = this.setTiles(tiles);
529
- const { width: newWidth, height: newHeight } = this.getDimensions(canvases);
530
- if (!shouldUpdate) {
531
- return;
532
- }
533
- if (!this.canvas) {
534
- return;
535
- }
536
- if (newHeight === 0) {
537
- this.canvas.height = 0;
538
- return;
539
- }
540
- if (this.canvas.height !== newHeight) {
541
- this.canvas.height = newHeight;
476
+ lockFrame,
477
+ tilesPerLine,
478
+ handleExportFrame,
479
+ scaleFactor
480
+ } = params;
481
+ const canvases = Object.entries(tiles).reduce((acc, [key, channelTiles]) => {
482
+ if (!channelTiles?.length) {
483
+ return acc;
542
484
  }
543
- if (this.canvas.width !== newWidth) {
544
- this.canvas.width = newWidth;
545
- }
546
- const context = this.canvas?.getContext("2d");
547
- if (!context) {
548
- return;
549
- }
550
- this.blendCanvases(context, canvases);
551
- }
552
- setPalette(palette) {
553
- if (!palette) {
554
- return false;
555
- }
556
- if (JSON.stringify(this.palette) === JSON.stringify(palette)) {
557
- return false;
558
- }
559
- this.palette = palette;
560
- return true;
561
- }
562
- setCanvas(canvas) {
563
- if (this.canvas === canvas) {
564
- return false;
565
- }
566
- this.canvas = canvas;
567
- return true;
568
- }
569
- setLockFrame(lockFrame) {
570
- if (lockFrame !== this.lockFrame) {
571
- this.lockFrame = lockFrame;
572
- return true;
573
- }
574
- return false;
575
- }
576
- setTiles(tiles) {
577
- return channels.reduce((acc, key) => {
578
- const channel = this.channels[key];
579
- channel.tiles = tiles[key];
580
- const channelColors = this.palette[key];
581
- const paletteFunction = paletteTemplates[key];
582
- if (!channel.tiles || !channelColors) {
583
- return acc;
584
- }
585
- const palette = [
586
- paletteFunction(channelColors[3]),
587
- paletteFunction(channelColors[2]),
588
- paletteFunction(channelColors[1]),
589
- paletteFunction(channelColors[0])
590
- ];
591
- channel.decoder.update({
592
- canvas: channel.canvas,
593
- tiles: channel.tiles,
594
- framePalette: this.lockFrame ? BW_PALETTE_HEX : palette,
595
- palette
596
- });
597
- return {
598
- ...acc,
599
- [key]: channel.canvas
600
- };
601
- }, {});
602
- }
603
- blendCanvases(targetContext, sourceCanvases) {
604
- channels.forEach((key) => {
605
- const sourceCanvas = sourceCanvases[key];
606
- if (sourceCanvas && sourceCanvas.width && sourceCanvas.height) {
607
- if (key === ChannelKey.N) {
608
- if (this.palette.blend === BlendMode.NORMAL) {
609
- return;
610
- }
611
- targetContext.globalCompositeOperation = blendModeNewName(this.palette.blend);
612
- } else {
613
- targetContext.globalCompositeOperation = "lighter";
614
- }
615
- targetContext.drawImage(sourceCanvas, 0, 0);
616
- }
485
+ const channelKey = key;
486
+ const channelShades = palette[channelKey] || RGBN_SHADES;
487
+ const channelPalette = singleChannelPalette(channelShades, channelKey);
488
+ const lockFramePalette = lockFrame ? singleChannelPalette(RGBN_SHADES, channelKey) : channelPalette;
489
+ const {
490
+ data,
491
+ dimensions
492
+ } = getRawMonochromeImageData({
493
+ imagePalette: channelPalette,
494
+ framePalette: lockFramePalette,
495
+ handleExportFrame,
496
+ imageStartLine,
497
+ scaleFactor,
498
+ tiles: channelTiles,
499
+ tilesPerLine
617
500
  });
618
- }
619
- getScaledCanvas(scaleFactor, handleExportFrame = ExportFrameMode.FRAMEMODE_KEEP) {
620
- const canvas = this.canvasCreator();
621
- const canvases = channels.reduce((acc, key) => {
622
- const channel = this.channels[key];
623
- const channelCanvas = channel.decoder.getScaledCanvas(scaleFactor, handleExportFrame);
624
- return {
625
- ...acc,
626
- [key]: channelCanvas
627
- };
628
- }, {});
629
- const { width, height } = this.getDimensions(canvases);
630
- canvas.width = width;
631
- canvas.height = height;
501
+ const canvas = canvasCreator();
502
+ canvas.width = dimensions.width;
503
+ canvas.height = dimensions.height;
632
504
  const context = canvas.getContext("2d");
633
- if (!context) {
634
- throw new Error("no canvas context");
635
- }
636
- context.fillStyle = "#000000";
637
- context.fillRect(0, 0, 500, 500);
638
- this.blendCanvases(context, canvases);
639
- return canvas;
640
- }
641
- getDimensions(canvases) {
642
- return Object.values(canvases).reduce((acc, current) => {
643
- if (current.width === 0 || current.height === 0) {
644
- return acc;
645
- }
646
- return {
647
- width: Math.max(current.width, acc.width),
648
- height: Math.max(current.height, acc.height)
649
- };
650
- }, { width: 0, height: 0 });
651
- }
652
- }
505
+ const imageData = new ImageData(data, dimensions.width, dimensions.height);
506
+ context.putImageData(imageData, 0, 0);
507
+ return {
508
+ ...acc,
509
+ [channelKey]: canvas
510
+ };
511
+ }, {});
512
+ return blendCanvases(canvases, palette.blend || BlendMode.NORMAL, canvasCreator);
513
+ };
514
+ const getRGBNImageUrl = async (params, canvasCreator = createCanvasElement) => {
515
+ const urlCache = new UrlCache();
516
+ const fullParams = getFullParams(params);
517
+ const hash = ohash.hash(fullParams);
518
+ const cachedUrl = await urlCache.getUrl(hash);
519
+ if (cachedUrl) {
520
+ return cachedUrl;
521
+ }
522
+ const rawOutput = getRawRGBNImageData(fullParams, canvasCreator);
523
+ return dataUrlFromRawOutput(rawOutput, fullParams.scaleFactor, hash, canvasCreator);
524
+ };
653
525
 
654
526
  const maxTiles = (rgbnTiles) => Math.max(...channels.map((key) => rgbnTiles[key]?.length || 0));
655
527
 
528
+ exports.BLACK = BLACK;
529
+ exports.BLACK_LINE = BLACK_LINE;
656
530
  exports.BW_PALETTE = BW_PALETTE;
657
531
  exports.BW_PALETTE_HEX = BW_PALETTE_HEX;
658
532
  exports.BlendMode = BlendMode;
659
533
  exports.ChannelKey = ChannelKey;
660
- exports.Decoder = Decoder;
661
534
  exports.ExportFrameMode = ExportFrameMode;
662
- exports.RGBNDecoder = RGBNDecoder;
535
+ exports.FRAME_WIDTH = FRAME_WIDTH;
536
+ exports.RGBN_SHADES = RGBN_SHADES;
663
537
  exports.SKIP_LINE = SKIP_LINE;
538
+ exports.TILES_PER_COLUMN = TILES_PER_COLUMN;
539
+ exports.TILES_PER_LINE = TILES_PER_LINE;
540
+ exports.TILE_PIXEL_HEIGHT = TILE_PIXEL_HEIGHT;
541
+ exports.TILE_PIXEL_WIDTH = TILE_PIXEL_WIDTH;
542
+ exports.UrlCache = UrlCache;
543
+ exports.WHITE = WHITE;
544
+ exports.WHITE_LINE = WHITE_LINE;
664
545
  exports.blendModeNewName = blendModeNewName;
546
+ exports.channels = channels;
665
547
  exports.decodeTile = decodeTile;
548
+ exports.defaultRGBNPalette = defaultRGBNPalette;
549
+ exports.getDimensions = getDimensions$1;
550
+ exports.getMonochromeImageUrl = getMonochromeImageUrl;
551
+ exports.getRGBNImageUrl = getRGBNImageUrl;
666
552
  exports.getRGBValue = getRGBValue;
553
+ exports.getRawMonochromeImageData = getRawMonochromeImageData;
554
+ exports.getRawRGBNImageData = getRawRGBNImageData;
667
555
  exports.maxTiles = maxTiles;
556
+ exports.scaleRawImageData = scaleRawImageData;
668
557
  exports.tileIndexIsPartOfFrame = tileIndexIsPartOfFrame;