diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..8108d63 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,28 @@ +--- +name: Bug report +about: Create a report to help us improve +title: "[BUG]" +labels: bug + +--- + +**Describe the bug** +A clear and concise description of what the bug is. + +**To Reproduce** +Steps to reproduce the behavior: +1. ... + +**Expected behavior** +A clear and concise description of what you expected to happen. + +**Screenshots** +If applicable, add screenshots to help explain your problem. + +**Platform:** + - OS: [e.g. iOS, Windows] + - Environment [e.g. Chrome, Firefox, NodeJS, Deno] + - Version [e.g. 1.0.1, 1.1.20] + +**Additional context** +Add any other context about the problem here. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000..c441779 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,16 @@ +--- +name: Feature request +about: Suggest an idea for this project +title: "[FR]" +labels: enhancement + +--- + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Additional context** +Add any other context or screenshots about the feature request here. diff --git a/.github/workflows/node.yml b/.github/workflows/node.yml index 4d3f188..dc9eab1 100644 --- a/.github/workflows/node.yml +++ b/.github/workflows/node.yml @@ -13,7 +13,7 @@ jobs: strategy: matrix: - version: [14.x, 15.x, 16.x] + version: [20.x, 22.x, 23.x, 24.x] os: [macos-latest, ubuntu-latest, windows-latest] steps: @@ -22,4 +22,4 @@ jobs: with: node-version: ${{ matrix.version }} - - run: npm test \ No newline at end of file + - run: npm test diff --git a/.gitignore b/.gitignore index 0f7433d..a2e0e01 100644 --- a/.gitignore +++ b/.gitignore @@ -3,4 +3,6 @@ old/ coverage/ .DS_Store .nyc_output/ -.node_modules/ \ No newline at end of file +.node_modules/ +bench/node_modules/ +bench/package-lock.json \ No newline at end of file diff --git a/ImageScript.d.ts b/ImageScript.d.ts new file mode 100644 index 0000000..dda0c78 --- /dev/null +++ b/ImageScript.d.ts @@ -0,0 +1,954 @@ +export class Image { + private __width__: number; + private __height__: number; + private __buffer__: ArrayBuffer; + private __view__: DataView; + private __u32__: Uint32Array; + bitmap: Uint8ClampedArray; + + constructor(width: number, height: number); + + private toString(): `Image<${number}x${number}>`; + + get width(): number; + + get height(): number; + + *[Symbol.iterator](): void; + + *iterateWithColors(): Generator< + [x: number, y: number, color: number], + void, + unknown +>; + static rgbaToColor(r: number, g: number, b: number, a: number): number; + + static rgbToColor(r: number, g: number, b: number): number; + + static hslaToColor(h: number, s: number, l: number, a: number): number; + + static hslToColor(h: number, s: number, l: number): number; + + static rgbaToHSLA(r: number, g: number, b: number, a: number): number[]; + + static colorToRGBA(color: number): number[]; + + static colorToRGB(color: number): number[]; + + getPixelAt(x: number, y: number): number; + + getRGBAAt(x: number, y: number): Uint8ClampedArray; + + setPixelAt(x: number, y: number, pixelColor: number): this; + + private __set_pixel__(x: number, y: number, pixelColor: number): void; + + private __check_boundaries__(x: number, y: number): void; + + private static get __out_of_bounds__(): string; + + /** + * Fills the entire image with the supplied color. + * + * @param color + */ + fill(color: number | ColorFunction): this; + + clone(): Image; + + /** + * Use + * {@link https://en.wikipedia.org/wiki/Image_scaling#Nearest-neighbor_interpolation Nearest-neighbor} + * resizing. + */ + static get RESIZE_NEAREST_NEIGHBOR(): "RESIZE_NEAREST_NEIGHBOR"; + + /** + * Used for automatically preserving an image's aspect ratio when resizing. + */ + static get RESIZE_AUTO(): -1; + + /** + * Resizes the image by the given factor. + * + * @param factor Fraction, where: + * - `0.5` is "50%" (half) + * - `1.0` is "100%" (same size) + * - `2.0` is "200%" (double) + * @param mode Default: {@link Image.RESIZE_NEAREST_NEIGHBOR} + */ + scale(factor: number, mode?: ResizeMode): this; + + private __scale__(factor: number, mode?: ResizeMode); + + /** + * Resizes the image to the given dimensions. + * Use {@link Image.RESIZE_AUTO} as either width or height to automatically + * preserve the aspect ratio. + * + * @param width The new width. + * @param height The new height. + * @param mode Default: {@link Image.RESIZE_NEAREST_NEIGHBOR} + */ + resize(width: number, height: number, mode?: ResizeMode): this; + + /** + * Resizes the image so it is contained in the given bounding box. + * Can return an image with one axis smaller than the given bounding box. + * + * @param width The width of the bounding box + * @param height The height of the bounding box + * @param mode Default: {@link Image.RESIZE_NEAREST_NEIGHBOR} + */ + contain(width: number, height: number, mode?: ResizeMode): this; + + /** + * Resizes the image so it is contained in the given bounding box, placing it in the center of the given bounding box. + * Always returns the exact dimensions of the bounding box. + * + * @param width The width of the bounding box + * @param height The height of the bounding box + * @param mode Default: {@link Image.RESIZE_NEAREST_NEIGHBOR} + */ + fit(width: number, height: number, mode?: ResizeMode): this; + + /** + * Resizes the image so it covers the given bounding box, cropping the overflowing edges. + * Always returns the exact dimensions of the bounding box. + * + * @param width The width of the bounding box + * @param height The height of the bounding box + * @param mode Default: {@link Image.RESIZE_NEAREST_NEIGHBOR} + */ + cover(width: number, height: number, mode?: ResizeMode): this; + + private __resize__(width: number, height: number, mode?: ResizeMode): this; + + private __resize_nearest_neighbor__(width: number, height: number): this; + + crop(x: number, y: number, width: number, height: number): this; + + private __crop__(x: number, y: number, width: number, height: number): this; + + /** + * Draws a box at the specified coordinates. + */ + drawBox( + x: number, + y: number, + width: number, + height: number, + color: number | ColorFunction + ): this; + + private __fast_box__( + x: number, + y: number, + width: number, + height: number, + color: number + ): this; + + /** + * Draws a circle at the specified coordinates with the specified radius. + */ + drawCircle( + x: number, + y: number, + radius: number, + color: number | ColorFunction + ): this; + + /** + * Crops the image into a circle. + * + * @param max Whether to use the larger dimension for the size. Default: `false` + * @param feathering How much feathering to apply to the edges. Default: `0` + */ + cropCircle(max?: boolean, feathering?: number): this; + + /** + * Sets the image's opacity. + * + * @param opacity `0`-`1`, where `0` is completely transparent and + * `1` is completely opaque. + * @param absolute Whether to scale the current opacity (`false`) or + * just set the new opacity (`true`). Default: `false` + */ + opacity(opacity: number, absolute?: boolean): this; + + /** + * Set the red channel's saturation value. + * + * @param saturation `0`-`1` + * @param absolute Whether to scale the current saturation (`false`) or + * just set the new saturation (`true`). Default: `false` + */ + red(saturation: number, absolute?: boolean): this; + + /** + * Set the green channel's saturation value. + * + * @param saturation `0`-`1` + * @param absolute Whether to scale the current saturation (`false`) or + * just set the new saturation (`true`). Default: `false` + */ + green(saturation: number, absolute?: boolean): this; + + /** + * Set the blue channel's saturation value. + * + * @param saturation `0`-`1` + * @param absolute Whether to scale the current saturation (`false`) or + * just set the new saturation (`true`). Default: `false` + */ + blue(saturation: number, absolute?: boolean): this; + + private __set_channel_value__( + value: number, + absolute: boolean, + offset: number + ): void; + + /** + * Sets the brightness of the image. + * + * @param value `0`-`1` + * @param absolute Whether to scale the current lightness (`false`) or + * just set the new lightness (`true`). Default: `false` + */ + lightness(value: number, absolute?: boolean): this; + + /** + * Sets the saturation of the image. + * + * @param value `0`-`1` + * @param absolute Whether to scale the current saturation (`false`) or + * just set the new saturation (`true`). Default: `false` + */ + saturation(value: number, absolute?: boolean): this; + + /** + * Composites (overlays) the {@link source} onto this image at the + * specified coordinates. + */ + composite(source: this, x?: number, y?: number): this; + + /** + * Inverts the image's colors. + */ + invert(): this; + + /** + * Inverts the image's value (lightness). + */ + invertValue(): this; + + /** + * Inverts the image's saturation. + */ + invertSaturation(): this; + + /** + * Inverts the image's hue. + */ + invertHue(): this; + + /** + * Shifts the image's hue. + */ + hueShift(degrees: number): this; + + /** + * Gets the average color of the image. + */ + averageColor(): number; + + /** + * Gets the image's dominant color. + * + * @param ignoreBlack Whether to ignore dark colors below the threshold. + * Default: `true` + * @param ignoreWhite Whether to ignore light colors above the threshold. + * Default: `true` + * @param bwThreshold The black/white threshold (`0`-`64`). + * Default: `0xf` (`15`) + */ + dominantColor( + ignoreBlack?: boolean, + ignoreWhite?: boolean, + bwThreshold?: number + ): number; + + /** + * Rotates the image the given amount of degrees. + * + * @param angle The angle to rotate the image for (in degrees) + * @param resize Whether to resize the image so it fits all pixels (`true`) or + * just ignore outlying pixels (`false`). Default: `true` + */ + rotate(angle: number, resize?: boolean): this; + + /** + * Flips / mirrors the image horizontally or vertically. + */ + flip(direction: "horizontal" | "vertical"): this; + + private __apply__(image: this | Frame): this | Frame; + + /** + * Creates a multi-point gradient generator. + * + * @param colors The gradient points to use + * (e.g. `{0: 0xff0000ff, 1: 0x00ff00ff}`). + * @returns The gradient generator. The function argument is the position + * in the gradient (`0`-`1`). + */ + static gradient(colors: { + [position: number]: number; + }): (position: number) => number; + + /** + * Rounds the image's corners. + * + * @param radius Default: `min(width, height) / 4` + */ + roundCorners(radius?: number): this; + + private static __gradient__(startColor: number, endColor: number): number; + + /** + * @param radius Default: `2` + */ + fisheye(radius?: number): this; + + /** + * Encodes the image into a PNG. + * + * @param compression `0`-`9`, where `0` is no compression and `9` is highest + * compression (default: `1`) + * @param metadata + */ + async encode( + compression?: PNGCompressionLevel, + metadata?: PNGMetadata + ): Promise; + async encode(metadata?: PNGMetadata): Promise; + + /** + * Encodes the image into a JPEG. + * + * @param quality `1`-`100`, where `1` is lowest quality (highest compression) + * and `100` is highest quality (lowest compression). Default: `90` + */ + async encodeJPEG(quality?: JPEGQuality): Promise; + + /** + * Encodes the image into a WEBP. + * + * @param quality `0`-`100`, or `null` for lossless. `0` is lowest quality + * (highest compression) and `100` is highest quality (lowest compression). + * Default: `null` + */ + async encodeWEBP(quality?: null | WEBPQuality): Promise; + + /** + * Decodes an image (PNG, JPEG or TIFF). + * + * @param data The binary data to decode + * @returns The decoded image + */ + static async decode(data: Buffer | Uint8Array): Promise; + + /** + * Scale the SVG by the given amount. For use with {@link Image.renderSVG}. + */ + static get SVG_MODE_SCALE(): 1; + + /** + * Scale the SVG to fit the given width. For use with {@link Image.renderSVG}. + */ + static get SVG_MODE_WIDTH(): 2; + + /** + * Scale the SVG to fit the given height. For use with {@link Image.renderSVG}. + */ + static get SVG_MODE_HEIGHT(): 3; + + /** + * Creates a new image from the given SVG. + * + * @param svg + * @param size + * @param mode {@link Image.SVG_MODE_SCALE}, {@link Image.SVG_MODE_WIDTH}, or + * {@link Image.SVG_MODE_HEIGHT}. + * + * @returns New bitmap image with the rendered {@link svg}. + */ + static async renderSVG( + svg: string, + size?: number, + mode?: SVGScaleMode + ): Promise; + + /** + * Creates a new image containing the rendered text. + * + * @param font TrueType (ttf/ttc) or OpenType (otf) font buffer to use. + * @param scale + * @param text + * @param color + * @param layout + * + * @returns New image with the rendered {@link text}. + */ + static async renderText( + font: Uint8Array, + scale: number, + text: string, + color?: number, + layout?: TextLayout + ): Promise; +} + +export type FrameDisposalModeName = "any" | "keep" | "previous" | "background"; + +export type FrameDisposalModeId = 0 | 1 | 2 | 3; + +/** + * Represents a frame in a GIF. + */ +export class Frame extends Image { + static get DISPOSAL_KEEP(): "keep"; + + static get DISPOSAL_PREVIOUS(): "previous"; + + static get DISPOSAL_BACKGROUND(): "background"; + + private static __convert_disposal_mode__( + mode: FrameDisposalModeName | FrameDisposalModeId + ): FrameDisposalModeId; + + /** + * Creates a new, blank frame. + * + * @param width + * @param height + * @param duration Milliseconds (default: `100`) + * @param xOffset Offset on the X-axis (default: `0`) + * @param yOffset Offset on the y-axis (default: `0`) + * @param disposalMode The frame's disposal mode (default: `'keep'`) + */ + constructor( + width: number, + height: number, + duration: number, + xOffset?: number, + yOffset?: number, + disposalMode?: FrameDisposalModeName | FrameDisposalModeId + ); + + /** + * Milliseconds. + */ + duration: number; + + xOffset: number; + + yOffset: number; + + get disposalMode(): FrameDisposalModeId; + + set disposalMode(disposalMode: FrameDisposalModeName | FrameDisposalModeId); + + toString(): `Frame<${number}x${number}x${number}ms>`; + + /** + * Converts an Image instance to a Frame, cloning it in the process + * @param image The image to create the frame from + * @param duration Milliseconds (default: `100`) + * @param xOffset Offset on the X-axis (default: `0`) + * @param yOffset Offset on the y-axis (default: `0`) + * @param disposalMode The frame's disposal mode (default: `'keep'`) + */ + static from( + image: Image, + duration?: number, + xOffset?: number, + yOffset?: number, + disposalMode?: FrameDisposalModeName | FrameDisposalModeId + ): Frame; + + /** + * @param width + * @param height + * @param mode Default: {@link Frame.DISPOSAL_KEEP} + */ + resize( + width: number, + height: number, + mode?: typeof Image.RESIZE_NEAREST_NEIGHBOR | string + ): Image; +} + +/** + * Represents a GIF image as an array of frames. + */ +export class GIF extends Array { + /** + * @param frames + * @param loopCount How many times to loop the GIF for (`-1` = unlimited). + */ + constructor(frames: Frame[], loopCount?: number); + + get width(): number; + + get height(): number; + + toString(): `GIF<${number}x${number}x${number}ms>`; + + *[Symbol.iterator](): Generator; + + slice(start: number, end: number): GIF; + + /** + * Milliseconds. + */ + get duration(): number; + + /** + * @param quality GIF quality `0`-`100` (default: `95`) + */ + async encode(quality?: GIFQuality): Promise; + + /** + * @param data + * @param onlyExtractFirstFrame Whether to end GIF decoding after the first + * frame (default: `false`) + */ + static async decode( + data: Buffer | Uint8Array, + onlyExtractFirstFrame?: boolean + ): Promise; + + /** + * @param width + * @param height + * @param mode Default: {@link Image.RESIZE_NEAREST_NEIGHBOR} + */ + resize(width: number, height: number, mode?: ResizeMode): void; +} + +export type WrapStyle = "word" | "char"; + +export type VerticalAlign = "left" | "center" | "right"; + +export type HorizontalAlign = "top" | "middle" | "bottom"; + +export class TextLayout { + /** + * @param options Defaults: + * ```js + * { + * maxWidth: Infinity, + * maxHeight: Infinity, + * wrapStyle: 'word', + * verticalAlign: 'left', + * horizontalAlign: 'top', + * wrapHardBreaks: true, + * } + * ``` + */ + constructor(options?: { + /** @default Infinity */ + maxWidth?: number; + + /** @default Infinity */ + maxHeight?: number; + + /** @default 'word' */ + wrapStyle?: WrapStyle; + + /** @default 'left' */ + verticalAlign?: VerticalAlign; + + /** @default 'top' */ + horizontalAlign?: HorizontalAlign; + + /** @default true */ + wrapHardBreaks?: boolean; + }); +} + +export type ImageTypeName = "png" | "jpeg" | "tiff" | "gif"; + +export class ImageType { + static getType(data: Buffer | Uint8Array): ImageTypeName | null; + + static isPNG(view: DataView): boolean; + + static isJPEG(view: DataView): boolean; + + static isTIFF(view: DataView): boolean; + + static isGIF(view: DataView): boolean; +} + +/** + * @param data + * @param onlyExtractFirstFrame Whether to end GIF decoding after the first + * frame (default: `false`) + */ +export function decode( + data: Uint8Array | Buffer, + onlyExtractFirstFrame?: boolean +): Promise; + +export type PNGMetadata = { + title?: string; + author?: string; + description?: string; + copyright?: string; + creationTime?: string | number | Date; + software?: string; + disclaimer?: string; + warning?: string; + source?: string; + comment?: string; +}; + +export type ColorFunction = (x: number, y: number) => number; + +export type ResizeMode = "RESIZE_NEAREST_NEIGHBOR" | -1; + +/** + * - `0` = no compression + * - `9` = highest compression + */ +export type PNGCompressionLevel = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9; + +/** + * {@link Image.SVG_MODE_SCALE}, {@link Image.SVG_MODE_WIDTH}, or + * {@link Image.SVG_MODE_HEIGHT}. + */ +export type SVGScaleMode = 1 | 2 | 3; + +/** + * - `0` = **lowest** quality (smallest file size) + * - `100` = **highest** quality (largest file size) + */ +export type WEBPQuality = + | 0 + | 1 + | 2 + | 3 + | 4 + | 5 + | 6 + | 7 + | 8 + | 9 + | 10 + | 11 + | 12 + | 13 + | 14 + | 15 + | 16 + | 17 + | 18 + | 19 + | 20 + | 21 + | 22 + | 23 + | 24 + | 25 + | 26 + | 27 + | 28 + | 29 + | 30 + | 31 + | 32 + | 33 + | 34 + | 35 + | 36 + | 37 + | 38 + | 39 + | 40 + | 41 + | 42 + | 43 + | 44 + | 45 + | 46 + | 47 + | 48 + | 49 + | 50 + | 51 + | 52 + | 53 + | 54 + | 55 + | 56 + | 57 + | 58 + | 59 + | 60 + | 61 + | 62 + | 63 + | 64 + | 65 + | 66 + | 67 + | 68 + | 69 + | 70 + | 71 + | 72 + | 73 + | 74 + | 75 + | 76 + | 77 + | 78 + | 79 + | 80 + | 81 + | 82 + | 83 + | 84 + | 85 + | 86 + | 87 + | 88 + | 89 + | 90 + | 91 + | 92 + | 93 + | 94 + | 95 + | 96 + | 97 + | 98 + | 99 + | 100; + +/** + * - `0` = **lowest** quality (smallest file size) + * - `100` = **highest** quality (largest file size) + */ +export type JPEGQuality = + | 1 + | 2 + | 3 + | 4 + | 5 + | 6 + | 7 + | 8 + | 9 + | 10 + | 11 + | 12 + | 13 + | 14 + | 15 + | 16 + | 17 + | 18 + | 19 + | 20 + | 21 + | 22 + | 23 + | 24 + | 25 + | 26 + | 27 + | 28 + | 29 + | 30 + | 31 + | 32 + | 33 + | 34 + | 35 + | 36 + | 37 + | 38 + | 39 + | 40 + | 41 + | 42 + | 43 + | 44 + | 45 + | 46 + | 47 + | 48 + | 49 + | 50 + | 51 + | 52 + | 53 + | 54 + | 55 + | 56 + | 57 + | 58 + | 59 + | 60 + | 61 + | 62 + | 63 + | 64 + | 65 + | 66 + | 67 + | 68 + | 69 + | 70 + | 71 + | 72 + | 73 + | 74 + | 75 + | 76 + | 77 + | 78 + | 79 + | 80 + | 81 + | 82 + | 83 + | 84 + | 85 + | 86 + | 87 + | 88 + | 89 + | 90 + | 91 + | 92 + | 93 + | 94 + | 95 + | 96 + | 97 + | 98 + | 99 + | 100; + +/** + * - `0` = **lowest** quality (smallest file size) + * - `100` = **highest** quality (largest file size) + */ +export type GIFQuality = + | 0 + | 1 + | 2 + | 3 + | 4 + | 5 + | 6 + | 7 + | 8 + | 9 + | 10 + | 11 + | 12 + | 13 + | 14 + | 15 + | 16 + | 17 + | 18 + | 19 + | 20 + | 21 + | 22 + | 23 + | 24 + | 25 + | 26 + | 27 + | 28 + | 29 + | 30 + | 31 + | 32 + | 33 + | 34 + | 35 + | 36 + | 37 + | 38 + | 39 + | 40 + | 41 + | 42 + | 43 + | 44 + | 45 + | 46 + | 47 + | 48 + | 49 + | 50 + | 51 + | 52 + | 53 + | 54 + | 55 + | 56 + | 57 + | 58 + | 59 + | 60 + | 61 + | 62 + | 63 + | 64 + | 65 + | 66 + | 67 + | 68 + | 69 + | 70 + | 71 + | 72 + | 73 + | 74 + | 75 + | 76 + | 77 + | 78 + | 79 + | 80 + | 81 + | 82 + | 83 + | 84 + | 85 + | 86 + | 87 + | 88 + | 89 + | 90 + | 91 + | 92 + | 93 + | 94 + | 95 + | 96 + | 97 + | 98 + | 99 + | 100; diff --git a/ImageScript.js b/ImageScript.js index bdb025e..62197e5 100644 --- a/ImageScript.js +++ b/ImageScript.js @@ -1,11 +1,13 @@ const png = require('./png/node.js'); const mem = require('./utils/mem.js'); -const codecs = require('./node/index.js'); const {version} = require('./package.json'); +const codecs = require('./codecs/node/index.js'); +const { default: v2 } = require('./v2/framebuffer.js'); // old const svglib = require('./wasm/node/svg.js'); const giflib = require('./wasm/node/gif.js'); +const pnglib = require('./wasm/node/png.js'); const fontlib = require('./wasm/node/font.js'); const jpeglib = require('./wasm/node/jpeg.js'); const tifflib = require('./wasm/node/tiff.js'); @@ -82,26 +84,16 @@ class Image { * @yields {number[]} The coordinates of the pixel ([x, y]) * @returns {void} */ - * [Symbol.iterator]() { - for (let y = 1; y <= this.height; y++) { - for (let x = 1; x <= this.width; x++) { - yield [x, y]; - } - } + *[Symbol.iterator]() { + for (const x of new v2(this.width, this.height, this.bitmap)[Symbol.iterator]()) yield (x[0]++, x[1]++, x) } /** * Yields an [x, y, color] array for every pixel in the image * @yields {number[]} The coordinates and color of the pixel ([x, y, color]) */ - * iterateWithColors() { - let offset = 0; - for (let y = 1; y <= this.height; y++) { - for (let x = 1; x <= this.width; x++) { - yield [x, y, this.__view__.getUint32(offset, false)]; - offset += 4; - } - } + *iterateWithColors() { + for (const x of new v2(this.width, this.height, this.bitmap).pixels('int')) yield (x[0]++, x[1]++, x); } /** @@ -319,19 +311,7 @@ class Image { * @returns {Image} */ fill(color) { - const type = typeof color; - if (type !== 'function') { - this.__view__.setUint32(0, color, false); - this.__u32__.fill(this.__u32__[0]); - } else { - let offset = 0; - for (let y = 1; y <= this.height; y++) { - for (let x = 1; x <= this.width; x++) { - this.__view__.setUint32(offset, color(x, y), false); - offset += 4; - } - } - } + new v2(this.width, this.height, this.bitmap).fill(color); return this; } @@ -392,6 +372,48 @@ class Image { return this.__apply__(image); } + /** + * Resizes the image so it is contained in the given bounding box. + * Can return an image with one axis smaller than the given bounding box. + * @param {number} width The width of the bounding box + * @param {number} height The height of the bounding box + * @param {string} [mode=Image.RESIZE_NEAREST_NEIGHBOR] The resizing mode to use + * @returns {Image} The resized image + */ + contain(width, height, mode = Image.RESIZE_NEAREST_NEIGHBOR) { + const scaleFactor = width / height > this.width / this.height ? height / this.height : width / this.width; + return this.scale(scaleFactor, mode); + } + + /** + * Resizes the image so it is contained in the given bounding box, placing it in the center of the given bounding box. + * Always returns the exact dimensions of the bounding box. + * @param {number} width The width of the bounding box + * @param {number} height The height of the bounding box + * @param {string} [mode=Image.RESIZE_NEAREST_NEIGHBOR] The resizing mode to use + * @returns {Image} The resized image + */ + fit(width, height, mode = Image.RESIZE_NEAREST_NEIGHBOR) { + const result = new Image(width, height); + this.contain(width, height, mode); + result.composite(this, (width - this.width) / 2, (height - this.height) / 2); + return this.__apply__(result); + } + + /** + * Resizes the image so it covers the given bounding box, cropping the overflowing edges. + * Always returns the exact dimensions of the bounding box. + * @param {number} width The width of the bounding box + * @param {number} height The height of the bounding box + * @param {string} [mode=Image.RESIZE_NEAREST_NEIGHBOR] The resizing mode to use + * @returns {Image} The resized image + */ + cover(width, height, mode = Image.RESIZE_NEAREST_NEIGHBOR) { + const scaleFactor = width / height > this.width / this.height ? width / this.width : height / this.height; + const result = this.scale(scaleFactor, mode); + return result.crop((result.width - width) / 2, (result.height - height) / 2, width, height); + } + /** @private */ __resize__(width, height, mode = Image.RESIZE_NEAREST_NEIGHBOR) { if (width === Image.RESIZE_AUTO && height === Image.RESIZE_AUTO) throw new Error('RESIZE_AUTO can only be used for either width or height, not for both'); @@ -420,18 +442,9 @@ class Image { */ __resize_nearest_neighbor__(width, height) { const image = new this.constructor(width, height); + const frame = new v2(this.width, this.height, this.bitmap).resize('nearest', width, height); - for (let y = 0; y < height; y++) { - for (let x = 0; x < width; x++) { - const ySrc = Math.floor((y * this.height) / height); - const xSrc = Math.floor((x * this.width) / width); - - const destPos = (y * width + x) * 4; - const srcPos = (ySrc * this.width + xSrc) * 4; - - image.__view__.setUint32(destPos, this.__view__.getUint32(srcPos, false), false); - } - } + image.bitmap.set(frame.u8); return image; } @@ -565,19 +578,7 @@ class Image { * @returns {Image} */ cropCircle(max = false, feathering = 0) { - const rad = Math[max ? 'max' : 'min'](this.width, this.height) / 2; - const radSquared = rad ** 2; - const centerX = this.width / 2; - const centerY = this.height / 2; - - for (const [x, y] of this) { - const distanceFromCenter = (x - centerX) ** 2 + (y - centerY) ** 2; - const alphaIdx = ((y - 1) * this.width + (x - 1)) * 4 + 3; - if (distanceFromCenter > radSquared) - this.bitmap[alphaIdx] = 0; - else if (feathering) - this.bitmap[alphaIdx] *= Math.max(0, Math.min(1, 1 - (distanceFromCenter / radSquared) * feathering ** (1 / 2))); - } + new v2(this.width, this.height, this.bitmap).crop('circle', feathering); return this; } @@ -693,48 +694,11 @@ class Image { * @returns {Image} */ composite(source, x = 0, y = 0) { - x = ~~x; - y = ~~y; - - for (let yy = 0; yy < source.height; yy++) { - let y_offset = y + yy; - if (y_offset < 0) continue; - if (y_offset >= this.height) break; - - for (let xx = 0; xx < source.width; xx++) { - let x_offset = x + xx; - if (x_offset < 0) continue; - if (x_offset >= this.width) break; - - const offset = 4 * (x_offset + y_offset * this.width); - const fg = source.__view__.getUint32(4 * (xx + yy * source.width), false); - const bg = this.__view__.getUint32(offset, false); - - if ((fg & 0xff) === 0xff) this.__view__.setUint32(offset, fg, false); - else if ((fg & 0xff) === 0x00) this.__view__.setUint32(offset, bg, false); - else this.__view__.setUint32(offset, Image.__alpha_blend__(fg, bg), false); - } - } + new v2(this.width, this.height, this.bitmap).overlay(new v2(source.width, source.height, source.bitmap), x, y); return this; } - /** - * @private - * @param {number} fg - * @param {number} bg - * @returns {number} - */ - static __alpha_blend__(fg, bg) { - const fa = fg & 0xff; - const alpha = fa + 1; - const inv_alpha = 256 - fa; - const r = (alpha * (fg >>> 24) + inv_alpha * (bg >>> 24)) >> 8; - const b = (alpha * (fg >> 8 & 0xff) + inv_alpha * (bg >> 8 & 0xff)) >> 8; - const g = (alpha * (fg >> 16 & 0xff) + inv_alpha * (bg >> 16 & 0xff)) >> 8; - return (((r & 0xff) << 24) | ((g & 0xff) << 16) | ((b & 0xff) << 8) | (Math.max(fa, bg & 0xff) & 0xff)); - } - /** * Inverts the images colors * @returns {Image} @@ -857,110 +821,25 @@ class Image { * @param {boolean} resize Whether to resize the image so it fits all pixels or just ignore outlying pixels */ rotate(angle, resize = true) { - if (angle % 360 === 0) return this; - if (angle % 180 === 0) return this.__rotate_180__(); - - const rad = Math.PI * (angle / 180); - - const sin = Math.sin(rad); - const cos = Math.cos(rad); - - const width = resize - ? Math.abs(this.width * sin) + Math.abs(this.height * cos) - : this.width; - const height = resize - ? Math.abs(this.width * cos) + Math.abs(this.height * sin) - : this.height; + const frame = new v2(this.width, this.height, this.bitmap).rotate(360 - (angle % 360), resize); - const out = new Image(width, height); - - const out_cx = width / 2 - .5; - const out_cy = height / 2 - .5; - const src_cx = this.width / 2 - .5; - const src_cy = this.height / 2 - .5; - - let h = 0; - do { - let w = 0; - const ysin = src_cx - sin * (h - out_cy); - const ycos = src_cy + cos * (h - out_cy); - - do { - const xf = ysin + cos * (w - out_cx); - const yf = ycos + sin * (w - out_cx); - Image.__interpolate__(this, out, w, h, xf, yf); - } while (w++ < width); - } while (h++ < height); + const out = new Image(frame.width, frame.height); + out.bitmap.set(frame.u8); return this.__apply__(out); } /** - * @returns {Image} - * @private + * Flips / mirrors the image horizontally or vertically + * @param {'horizontal' | 'vertical'} direction The direction to flip */ - __rotate_180__() { - let offset = 0; - this.bitmap.reverse(); - while (offset < this.bitmap.length) this.bitmap.subarray(offset, offset += 4).reverse(); + flip(direction) { + const frame = new v2(this.width, this.height, this.bitmap).flip(direction); + this.bitmap.set(frame.u8); return this; } - /** - * @param {Image} src - * @param {Image} out - * @param {number} x0 - * @param {number} y0 - * @param {number} x1 - * @param {number} y1 - * @private - */ - static __interpolate__(src, out, x0, y0, x1, y1) { - const x2 = ~~x1; - const y2 = ~~y1; - const xq = x1 - x2; - const yq = y1 - y2; - const out_slice = out.bitmap.subarray(4 * (x0 + y0 * out.width), -4); - - const ref = { - r: 0, - g: 0, - b: 0, - a: 0, - }; - - Image.__pawn__(x2, y2, (1 - xq) * (1 - yq), ref, src); - Image.__pawn__(1 + x2, y2, xq * (1 - yq), ref, src); - Image.__pawn__(x2, 1 + y2, (1 - xq) * yq, ref, src); - Image.__pawn__(1 + x2, 1 + y2, xq * yq, ref, src); - - out_slice[3] = ref.a; - out_slice[0] = ref.r / ref.a; - out_slice[1] = ref.g / ref.a; - out_slice[2] = ref.b / ref.a; - } - - /** @private */ - static __pawn__(point0, point1, weight, ref, src) { - if ( - point0 > 0 - && point1 > 0 - && point0 < src.width - && point1 < src.height - ) { - const offset = 4 * (point0 + point1 * src.width); - const src_slice = src.bitmap.subarray(offset, offset + 4); - - const wa = weight * src_slice[3]; - - ref.a += wa; - ref.r += wa * src_slice[0]; - ref.g += wa * src_slice[1]; - ref.b += wa * src_slice[2]; - } - } - /** * @private * @param {Image|Frame} image @@ -1215,9 +1094,9 @@ class Image { const view = new DataView(data.buffer, data.byteOffset, data.byteLength); if (ImageType.isPNG(view)) { // PNG - const {width, height, pixels} = await png.decode(data); + const {width, height, framebuffer} = (await pnglib.init()).decode(data); image = new Image(width, height); - image.bitmap.set(pixels); + image.bitmap.set(framebuffer); } else if (ImageType.isJPEG(view)) { // JPEG const framebuffer = (await jpeglib.init()).decode(data); @@ -1401,8 +1280,6 @@ class Frame extends Image { if (isNaN(duration) || duration < 0) throw new RangeError('Invalid frame duration'); - disposalMode = Frame.__convert_disposal_mode__(disposalMode); - super(width, height); this.duration = duration; this.xOffset = xOffset; @@ -1410,6 +1287,22 @@ class Frame extends Image { this.disposalMode = disposalMode; } + /** + * The Frame's disposal mode + * @returns {number} + */ + get disposalMode() { + return this.__disposalMode__; + } + + /** + * Sets the frame's disposal mode, converting it to the internal numeric value. + * @param {string|number} disposalMode The frame's disposal mode + */ + set disposalMode(disposalMode) { + this.__disposalMode__ = Frame.__convert_disposal_mode__(disposalMode); + } + toString() { return `Frame<${this.width}x${this.height}x${this.duration}ms>`; } @@ -1427,8 +1320,6 @@ class Frame extends Image { if (!(image instanceof Image)) throw new TypeError('Invalid image passed'); - disposalMode = Frame.__convert_disposal_mode__(disposalMode); - const frame = new Frame(image.width, image.height, duration, xOffset, yOffset, disposalMode); frame.bitmap.set(image.bitmap); @@ -1456,7 +1347,7 @@ class GIF extends Array { /** * Creates a new GIF image. * @param {Frame[]} frames The frames to create the GIF from - * @param {number} [loopCount=0] How often to loop the GIF for (-1 = unlimited) + * @param {number} [loopCount=-1] How often to loop the GIF for (-1 = unlimited) * @property {number} loopCount How often the GIF will loop for */ constructor(frames, loopCount = -1) { @@ -1514,6 +1405,15 @@ class GIF extends Array { yield this[i]; } + slice(start, end) { + if (end === Infinity) + end = this.length; + const frames = new Array(end - start); + for (let i = 0; i < frames.length; i++) + frames[i] = this[i + start]; + return new GIF(frames, this.loopCount); + } + /** * The GIFs duration (in ms) * @return {number} @@ -1622,7 +1522,7 @@ class GIF extends Array { } else if (0 === mode || 1 === mode) { - t8.set(u8) + t8.set(u8); for (let y = 0 | 0; y < height; y++) { const y_offset = fx + gwidth * (y + fy) | 0; @@ -1690,7 +1590,7 @@ class TextLayout { if (!['top', 'middle', 'bottom'].includes(this.horizontalAlign)) throw new RangeError('Invalid horizontalAlign'); - this.wrapHardBreaks = wrapHardBreaks || true; + this.wrapHardBreaks = typeof wrapHardBreaks === 'undefined' ? true : wrapHardBreaks; if (typeof this.wrapHardBreaks !== 'boolean') throw new TypeError('Invalid wrapHardBreaks'); } @@ -1724,7 +1624,7 @@ class ImageType { * @returns {boolean} */ static isPNG(view) { - return view.getUint32(0, false) === MAGIC_NUMBERS.PNG; + return view.byteLength >= 4 && view.getUint32(0, false) === MAGIC_NUMBERS.PNG; } /** @@ -1732,7 +1632,7 @@ class ImageType { * @returns {boolean} */ static isJPEG(view) { - return (view.getUint32(0, false) >>> 8) === MAGIC_NUMBERS.JPEG; + return view.byteLength >= 4 && (view.getUint32(0, false) >>> 8) === MAGIC_NUMBERS.JPEG; } /** @@ -1740,7 +1640,7 @@ class ImageType { * @returns {boolean} */ static isTIFF(view) { - return view.getUint32(0, false) === MAGIC_NUMBERS.TIFF; + return view.byteLength >= 4 && view.getUint32(0, false) === MAGIC_NUMBERS.TIFF; } /** @@ -1748,7 +1648,7 @@ class ImageType { * @returns {boolean} */ static isGIF(view) { - return (view.getUint32(0, false) >>> 8) === MAGIC_NUMBERS.GIF; + return view.byteLength >= 4 && (view.getUint32(0, false) >>> 8) === MAGIC_NUMBERS.GIF; } } diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..5d2197d --- /dev/null +++ b/LICENSE @@ -0,0 +1,12 @@ +This software is licensed under the following license(s): +- GNU AFFERO GENERAL PUBLIC LICENSE, Version 3 +- MIT License + +== SPDX-License-Identifier: AGPL-3.0-or-later OR MIT == + +You may choose to comply with either one of the above +mentioned licenses, but a license must be chosen. + +The corresponding license files can be found in the projects +root directory, prefixed with LICENSE, suffixed with their +corresponding SPDX identifier. \ No newline at end of file diff --git a/LICENSE.AGPL-3.0 b/LICENSE.AGPL-3.0 new file mode 100644 index 0000000..ce0100f --- /dev/null +++ b/LICENSE.AGPL-3.0 @@ -0,0 +1,619 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS diff --git a/LICENSE.MIT b/LICENSE.MIT new file mode 100644 index 0000000..8f0286a --- /dev/null +++ b/LICENSE.MIT @@ -0,0 +1,19 @@ +Copyright (c) 2023 Mathis Mensing + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/README.md b/README.md index 17b22fb..4648c83 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,9 @@ # ImageScript ##### zero-dependency JavaScript image manipulation [![Discord Server](https://img.shields.io/discord/691713541262147687.svg?label=Discord&logo=discord&logoColor=ffffff&color=7389D8&labelColor=6A7EC2&style=for-the-badge)](https://discord.gg/8hPrwAH) -[![Documentation](https://img.shields.io/badge/Documentationn-informational?style=for-the-badge)](https://imagescript.dreadful.tech/) +[![Documentation](https://img.shields.io/badge/Documentation-informational?style=for-the-badge)](https://imagescript.matmen.dev/) [![Github](https://img.shields.io/badge/Github-Repository-181717?logo=github&style=for-the-badge)](https://github.com/matmen/ImageScript) +[![deno.land](https://shields.io/badge/deno.land-gray?logo=deno&style=for-the-badge)](https://deno.land/x/imagescript) [![NPM](https://nodei.co/npm/imagescript.png)](https://www.npmjs.com/package/imagescript) --- @@ -15,29 +16,34 @@ binaries for decoding and encoding. ### Features -- [Decoding images](https://imagescript.dreadful.tech/Image.html#.decode) +- [Decoding images](https://imagescript.matmen.dev/Image.html#.decode) - PNGs (grayscale, RGB, indexed colors) with and without alpha channels - JPEGs (grayscale, RGB, CMYK) - TIFFs -- [Decoding GIFs](https://imagescript.dreadful.tech/GIF.html#.decode) -- [Rendering SVGs](https://imagescript.dreadful.tech/Image.html#.renderSVG) -- [Rendering vector fonts](https://imagescript.dreadful.tech/Image.html#.renderText) -- Image manipulation functions ([crop](https://imagescript.dreadful.tech/Image.html#crop) - , [rotate](https://imagescript.dreadful.tech/Image.html#rotate) - , [composite](https://imagescript.dreadful.tech/Image.html#composite), ...) -- Color manipulation functions ([invert](https://imagescript.dreadful.tech/Image.html##invert) - , [hueShift](https://imagescript.dreadful.tech/Image.html##hueshift), ...) -- Color information functions ([averageColor](https://imagescript.dreadful.tech/Image.html#averageColor) - , [dominantColor](https://imagescript.dreadful.tech/Image.html#dominantColor), ...) -- Encoding images as [PNGs](https://imagescript.dreadful.tech/Image.html#encode) - , [JPEGs](https://imagescript.dreadful.tech/Image.html#encodejpeg) - , [WEBPs](https://imagescript.dreadful.tech/Image.html#encodeWEBP) - and [GIFs](https://imagescript.dreadful.tech/GIF.html#encode) +- [Decoding GIFs](https://imagescript.matmen.dev/GIF.html#.decode) +- [Rendering SVGs](https://imagescript.matmen.dev/Image.html#.renderSVG) +- [Rendering vector fonts](https://imagescript.matmen.dev/Image.html#.renderText) +- Image manipulation functions ([crop](https://imagescript.matmen.dev/Image.html#crop) + , [rotate](https://imagescript.matmen.dev/Image.html#rotate) + , [composite](https://imagescript.matmen.dev/Image.html#composite), ...) +- Color manipulation functions ([invert](https://imagescript.matmen.dev/Image.html##invert) + , [hueShift](https://imagescript.matmen.dev/Image.html##hueshift), ...) +- Color information functions ([averageColor](https://imagescript.matmen.dev/Image.html#averageColor) + , [dominantColor](https://imagescript.matmen.dev/Image.html#dominantColor), ...) +- Encoding images as [PNGs](https://imagescript.matmen.dev/Image.html#encode) + , [JPEGs](https://imagescript.matmen.dev/Image.html#encodejpeg) + , [WEBPs](https://imagescript.matmen.dev/Image.html#encodeWEBP) + and [GIFs](https://imagescript.matmen.dev/GIF.html#encode) --- ### Example +Check out one of these examples: +* **NodeJS**: [README image generation](https://github.com/matmen/ImageScript/blob/master/tests/readme.js) +* **Deno**: [README image generation](https://github.com/matmen/ImageScript/blob/deno/tests/readme.js) +* **Browser**: [Grayscale Conversion Example Page](https://github.com/matmen/ImageScript/blob/browser/example/index.html) (via CDN) + [![Example](https://github.com/matmen/ImageScript/raw/master/tests/targets/readme.png)](https://github.com/matmen/ImageScript/blob/master/tests/readme.js) --- diff --git a/bench/_.mjs b/bench/_.mjs new file mode 100644 index 0000000..91190e7 --- /dev/null +++ b/bench/_.mjs @@ -0,0 +1,166 @@ +// https://gist.github.com/evanwashere/7ee592870e46f80405b9776dcd56e1e8#file-bench-js + +const now = performance.now.bind(performance); + +function sort(a, b) { + if (a > b) return 1; + if (a < b) return -1; + + return 0; +}; + +function stats(n, avg, min, max, jit, all) { + return { + min: Math.ceil(min * 1e6), + max: Math.ceil(max * 1e6), + avg: Math.ceil(avg / n * 1e6), + jit: jit.map(x => Math.ceil(x * 1e6)), + '50th': Math.ceil(1e6 * all[Math.ceil(n * (50 / 100)) - 1]), + '75th': Math.ceil(1e6 * all[Math.ceil(n * (75 / 100)) - 1]), + '99th': Math.ceil(1e6 * all[Math.ceil(n * (99 / 100)) - 1]), + '99.5th': Math.ceil(1e6 * all[Math.ceil(n * (99.5 / 100)) - 1]), + '99.9th': Math.ceil(1e6 * all[Math.ceil(n * (99.9 / 100)) - 1]), + }; +} + +export function sync(n, fn) { + let avg = 0; + let min = Infinity; + let max = -Infinity; + const all = new Array(n); + const jit = new Array(10); + + warmup: { + let offset = 0; + let iterations = 10; + while (iterations--) { + const t1 = now(); + + fn(); + jit[offset++] = now() - t1; + } + + iterations = 1e3 - 10; + while (iterations--) fn(); + } + + measure: { + let offset = 0; + let iterations = n; + while (iterations--) { + const t1 = now(); + + fn(); + const t2 = now() - t1; + if (t2 < min) min = t2; + if (t2 > max) max = t2; + avg += (all[offset++] = t2); + } + } + + all.sort(sort); + return stats(n, avg, min, max, jit, all); +} + +export async function async(n, fn) { + let avg = 0; + let min = Infinity; + let max = -Infinity; + const all = new Array(n); + const jit = new Array(10); + + warmup: { + let offset = 0; + let iterations = 10; + while (iterations--) { + const t1 = now(); + + await fn(); + jit[offset++] = now() - t1; + } + + iterations = 1e3 - 10; + while (iterations--) await fn(); + } + + measure: { + let offset = 0; + let iterations = n; + while (iterations--) { + const t1 = now(); + + await fn(); + const t2 = now() - t1; + if (t2 < min) min = t2; + if (t2 > max) max = t2; + avg += (all[offset++] = t2); + } + } + + all.sort(sort); + return stats(n, avg, min, max, jit, all); +} + +export function format({ results, title = '', unit = 'ns', percentiles = true }) { + const h = '─'; + const v = '│'; + + let s = ''; + unit = `${unit}/iter`; + const rk = Object.keys(results); + const rv = Object.values(results); + const ra = rv.map(x => x.avg.toLocaleString('en-us')); + const r50 = rv.map(x => x['50th'].toLocaleString('en-us')); + const r75 = rv.map(x => x['75th'].toLocaleString('en-us')); + const r99 = rv.map(x => x['99th'].toLocaleString('en-us')); + const r995 = rv.map(x => x['99.5th'].toLocaleString('en-us')); + const r999 = rv.map(x => x['99.9th'].toLocaleString('en-us')); + const rmm = rv.map(x => [x.min.toLocaleString('en-us'), x.max.toLocaleString('en-us')]); + + const us = unit.length; + const rks = Math.max(...rk.map(x => x.length)); + const ras = Math.max(...ra.map(x => x.length)); + const r50s = Math.max(...r50.map(x => x.length)); + const r75s = Math.max(...r75.map(x => x.length)); + const r99s = Math.max(...r99.map(x => x.length)); + const r995s = Math.max(...r995.map(x => x.length)); + const r999s = Math.max(...r999.map(x => x.length)); + const rmns = Math.max(...rmm.map(x => x[0].length)); + const rmxs = Math.max(...rmm.map(x => x[1].length)); + + const bks = 1 + rks + 1; + const b50s = 1 + r50s + 1 + us + 1; + const b75s = 1 + r75s + 1 + us + 1; + const b99s = 1 + r99s + 1 + us + 1; + const b995s = 1 + r995s + 1 + us + 1; + const b999s = 1 + r999s + 1 + us + 1; + const bimms = 1 + rmns + 2 + rmxs + 1 + us + 1; + const bas = 1 + (ras + 1 + us) + 1 + bimms + 1; + const ls = 1 + bks + 1 + bas + 1 + b50s + 1 + b75s + 1 + b99s + 1 + b995s + 1 + b999s + 1; + + if (!percentiles) s += title ? ` ${title}` : ''; + + else { + s += ' '.repeat(3 + bks + bas); + s += '┌' + h.repeat(ls - 4 - bks - bas) + '┐'; + s += '\n' + ` ${title.padEnd(2 + bks + bas, ' ')}`; + } + + if (percentiles) s += v + + '50th'.padEnd((b50s + 4) / 2, ' ').padStart(b50s, ' ') + v + + '75th'.padEnd((b75s + 4) / 2, ' ').padStart(b75s, ' ') + v + + '99th'.padEnd((b99s + 4) / 2, ' ').padStart(b99s, ' ') + v + + '99.5th'.padEnd((b995s + 6) / 2, ' ').padStart(b995s, ' ') + v + + '99.9th'.padEnd((b999s + 6) / 2, ' ').padStart(b999s, ' ') + v; + + s += (title || percentiles ? '\n' : '') + '┌' + h.repeat(1 + bks + bas) + '┐' + (percentiles ? '├' + h.repeat(ls - 4 - bks - bas) + '┤' : ''); + + for (let i = 0; i < rk.length; i++) { + s += '\n' + v + ` ${rk[i].padEnd(rks, ' ')} ` + v + ` ${ra[i].padStart(ras, ' ')} ${unit} ${`(${rmm[i][0]}..${rmm[i][1]} ${unit})`.padStart(bimms, ' ')} ` + v + if (percentiles) s += v + ` ${r50[i].padStart(r50s, ' ')} ${unit} ` + v + ` ${r75[i].padStart(r75s, ' ')} ${unit} ` + v + ` ${r99[i].padStart(r99s, ' ')} ${unit} ` + v + ` ${r995[i].padStart(r995s, ' ')} ${unit} ` + v + ` ${r999[i].padStart(r999s, ' ')} ${unit} ` + v; + } + + s += '\n' + '└' + h.repeat(1 + bks + bas) + '┘' + (percentiles ? '└' + h.repeat(ls - 4 - bks - bas) + '┘' : ''); + + return s; +} \ No newline at end of file diff --git a/bench/all.mjs b/bench/all.mjs new file mode 100644 index 0000000..8272727 --- /dev/null +++ b/bench/all.mjs @@ -0,0 +1,4 @@ +import './flip.mjs'; +import './blur.mjs'; +import './resize.mjs'; +import './overlay.mjs'; \ No newline at end of file diff --git a/bench/blur.mjs b/bench/blur.mjs new file mode 100644 index 0000000..5211946 --- /dev/null +++ b/bench/blur.mjs @@ -0,0 +1,59 @@ +import { sync, async, format } from './_.mjs'; + +import jimp from 'jimp'; +import sharp from 'sharp'; +import v2 from '../v2/framebuffer.mjs'; +import * as imagers from '@evan/wasm/target/image/node.mjs'; +import * as v2_wasm from '@evan/wasm/target/imagescript/node.mjs'; + +{ + const rgba = new Uint8Array(4 * 256 * 256).map((_, i) => i % 256); + + const images = { + v2: new v2(256, 256, rgba), + imagers: imagers.framebuffer.from(256, 256, rgba), + v2_wasm: () => v2_wasm.framebuffer.from(256, 256, rgba), + sharp: sharp(rgba, { raw: { width: 256, height: 256, channels: 4 } }), + jimp: await new Promise(r => new jimp({ width: 256, height: 256, data: rgba }, (_, i) => r(i))), + }; + + console.log(format({ + percentiles: false, + title: 'blur (5.0f/256x256)', + + results: { + jimp: sync(1e4, () => images.jimp.clone().blur(5)), + imagescript: sync(1e4, () => images.v2.clone().blur('gaussian')), + sharp: await async(1e4, () => images.sharp.clone().blur(5).toBuffer()), + 'image-rs (wasm)': sync(1e4, () => imagers.blur(images.imagers, 5).drop()), + 'imagescript-rs (wasm)': sync(1e4, () => { let i = images.v2_wasm(); v2_wasm.blur(i, 5); i.drop() }), + }, + })); + + images.imagers.drop(); +} + +{ + const rgba = new Uint8Array(4 * 1024 * 1024).map((_, i) => i % 256); + + const images = { + v2: new v2(1024, 1024, rgba), + imagers: imagers.framebuffer.from(1024, 1024, rgba), + v2_wasm: () => v2_wasm.framebuffer.from(1024, 1024, rgba), + sharp: sharp(rgba, { raw: { width: 1024, height: 1024, channels: 4 } }), + jimp: await new Promise(r => new jimp({ width: 1024, height: 1024, data: rgba }, (_, i) => r(i))), + }; + + console.log(format({ + percentiles: false, + title: 'blur (5.0f/1024x1024)', + + results: { + jimp: sync(1e4, () => images.jimp.clone().blur(5)), + imagescript: sync(1e4, () => images.v2.clone().blur('gaussian')), + sharp: await async(1e4, () => images.sharp.clone().blur(5).toBuffer()), + 'image-rs (wasm)': sync(1e4, () => imagers.blur(images.imagers, 5).drop()), + 'imagescript-rs (wasm)': sync(1e4, () => { let i = images.v2_wasm(); v2_wasm.blur(i, 5); i.drop() }), + }, + })); +} \ No newline at end of file diff --git a/bench/flip.mjs b/bench/flip.mjs new file mode 100644 index 0000000..c4eff9b --- /dev/null +++ b/bench/flip.mjs @@ -0,0 +1,63 @@ +import { sync, async, format } from './_.mjs'; + +import jimp from 'jimp'; +import sharp from 'sharp'; +import v2 from '../v2/framebuffer.mjs'; +import * as imagers from '@evan/wasm/target/image/node.mjs'; +import * as v2_wasm from '@evan/wasm/target/imagescript/node.mjs'; + +{ + const rgba = new Uint8Array(4 * 256 * 256).map((_, i) => i % 256); + + const images = { + v2: new v2(256, 256, rgba), + imagers: imagers.framebuffer.from(256, 256, rgba), + v2_wasm: v2_wasm.framebuffer.from(256, 256, rgba), + sharp: sharp(rgba, { raw: { width: 256, height: 256, channels: 4 } }), + jimp: await new Promise(r => new jimp({ width: 256, height: 256, data: rgba }, (_, i) => r(i))), + }; + + console.log(format({ + percentiles: false, + title: 'flip horizontal (256)', + + results: { + jimp: sync(1e4, () => images.jimp.flip(true, false)), + imagescript: sync(1e4, () => images.v2.flip('horizontal')), + sharp: await async(1e4, () => images.sharp.flip().toBuffer()), + 'image-rs (wasm)': sync(1e4, () => images.imagers.flip_horizontal()), + 'imagescript-rs (wasm)': sync(1e4, () => v2_wasm.flip_horizontal(images.v2_wasm)), + }, + })); + + images.v2_wasm.drop(); + images.imagers.drop(); +} + +{ + const rgba = new Uint8Array(4 * 256 * 256).map((_, i) => i % 256); + + const images = { + v2: new v2(256, 256, rgba), + imagers: imagers.framebuffer.from(256, 256, rgba), + v2_wasm: v2_wasm.framebuffer.from(256, 256, rgba), + sharp: sharp(rgba, { raw: { width: 256, height: 256, channels: 4 } }), + jimp: await new Promise(r => new jimp({ width: 256, height: 256, data: rgba }, (_, i) => r(i))), + }; + + console.log(format({ + percentiles: false, + title: 'flip vertical (256)', + + results: { + jimp: sync(1e4, () => images.jimp.flip(false, true)), + imagescript: sync(1e4, () => images.v2.flip('vertical')), + sharp: await async(1e4, () => images.sharp.flop().toBuffer()), + 'image-rs (wasm)': sync(1e4, () => images.imagers.flip_vertical()), + 'imagescript-rs (wasm)': sync(1e4, () => v2_wasm.flip_vertical(images.v2_wasm)), + }, + })); + + images.v2_wasm.drop(); + images.imagers.drop(); +} \ No newline at end of file diff --git a/bench/overlay.mjs b/bench/overlay.mjs new file mode 100644 index 0000000..ea968fe --- /dev/null +++ b/bench/overlay.mjs @@ -0,0 +1,35 @@ +import { sync, async, format } from './_.mjs'; + +import jimp from 'jimp'; +import sharp from 'sharp'; +import v2 from '../v2/framebuffer.mjs'; +import * as imagers from '@evan/wasm/target/image/node.mjs'; +import * as v2_wasm from '@evan/wasm/target/imagescript/node.mjs'; + +{ + const rgba = new Uint8Array(4 * 256 * 256).map((_, i) => i % 256); + + const images = { + v2: new v2(256, 256, rgba), + imagers: imagers.framebuffer.from(256, 256, rgba), + v2_wasm: v2_wasm.framebuffer.from(256, 256, rgba), + sharp: sharp(rgba, { raw: { width: 256, height: 256, channels: 4 } }), + jimp: await new Promise(r => new jimp({ width: 256, height: 256, data: rgba }, (_, i) => r(i))), + }; + + console.log(format({ + percentiles: false, + title: 'overlay(256x256)', + + results: { + jimp: sync(1e4, () => images.jimp.composite(images.jimp, 0, 0)), + imagescript: sync(1e4, () => images.v2.overlay(images.v2, 0, 0)), + 'image-rs (wasm)': sync(1e4, () => images.imagers.overlay(images.imagers, 0, 0)), + 'imagescript-rs (wasm)': sync(1e4, () => v2_wasm.overlay(images.v2_wasm, images.v2_wasm, 0, 0)), + sharp: await async(1e4, () => images.sharp.composite([{ input: rgba, raw: { width: 256, height: 256, channels: 4 } }]).toBuffer()), + }, + })); + + images.v2_wasm.drop(); + images.imagers.drop(); +} \ No newline at end of file diff --git a/bench/package.json b/bench/package.json new file mode 100644 index 0000000..9b713a9 --- /dev/null +++ b/bench/package.json @@ -0,0 +1,7 @@ +{ + "dependencies": { + "jimp": "^0.16.1", + "sharp": "^0.29.2", + "@evan/wasm": "^0.0.92" + } +} \ No newline at end of file diff --git a/bench/readme.md b/bench/readme.md new file mode 100644 index 0000000..de13077 --- /dev/null +++ b/bench/readme.md @@ -0,0 +1,64 @@ +these benchmarks are purely for v2 progress tracking + +`node all.mjs` +```js + resize linear (256 -> 1024) +┌─────────────────────────────────────────────────────────────────────────────┐ +│ imagescript │ 19,503,902 ns/iter (18,861,626..27,912,168 ns/iter) │ +│ imagescript-rs (wasm) │ 17,713,101 ns/iter (17,476,625..23,760,793 ns/iter) │ +└─────────────────────────────────────────────────────────────────────────────┘ + resize cubic (256 -> 1024) +┌────────────────────────────────────────────────────────────────────────────────┐ +│ imagescript │ 235,246,467 ns/iter (229,790,251..354,907,209 ns/iter) │ +│ sharp │ 14,342,381 ns/iter (10,830,958..39,727,583 ns/iter) │ +│ imagescript-rs (wasm) │ 63,684,581 ns/iter (62,884,708..75,180,751 ns/iter) │ +└────────────────────────────────────────────────────────────────────────────────┘ + flip horizontal (256) +┌─────────────────────────────────────────────────────────────────────────────────┐ +│ jimp │ 1,259,846 ns/iter (1,209,542..2,151,208 ns/iter) │ +│ imagescript │ 26,333 ns/iter (24,626..93,501 ns/iter) │ +│ sharp │ 24,134,341 ns/iter (274,959..210,144,563,500 ns/iter) │ +│ image-rs (wasm) │ 43,797 ns/iter (43,501..74,293 ns/iter) │ +│ imagescript-rs (wasm) │ 14,309 ns/iter (13,959..49,333 ns/iter) │ +└─────────────────────────────────────────────────────────────────────────────────┘ + flip vertical (256) +┌───────────────────────────────────────────────────────────────────────────┐ +│ jimp │ 1,281,557 ns/iter (1,223,292..7,604,917 ns/iter) │ +│ imagescript │ 54,151 ns/iter (53,333..89,959 ns/iter) │ +│ sharp │ 2,552,946 ns/iter (513,959..10,188,876 ns/iter) │ +│ image-rs (wasm) │ 30,475 ns/iter (30,167..88,250 ns/iter) │ +│ imagescript-rs (wasm) │ 13,747 ns/iter (13,542..27,042 ns/iter) │ +└───────────────────────────────────────────────────────────────────────────┘ + overlay(256x256) +┌─────────────────────────────────────────────────────────────────────────────────┐ +│ jimp │ 3,428,386 ns/iter (3,372,335..5,125,459 ns/iter) │ +│ imagescript │ 259,099 ns/iter (256,583..310,334 ns/iter) │ +│ image-rs (wasm) │ 541,678 ns/iter (533,166..1,509,710 ns/iter) │ +│ imagescript-rs (wasm) │ 143,653 ns/iter (137,293..1,242,793 ns/iter) │ +│ sharp │ 28,689,423 ns/iter (1,837,000..210,144,590,042 ns/iter) │ +└─────────────────────────────────────────────────────────────────────────────────┘ + resize nearest (256 -> 1024) +┌───────────────────────────────────────────────────────────────────────────────┐ +│ imagescript │ 1,452,792 ns/iter (1,327,334..13,043,958 ns/iter) │ +│ jimp │ 6,053,008 ns/iter (5,835,042..9,540,835 ns/iter) │ +│ sharp │ 6,209,299 ns/iter (2,089,376..15,344,367,876 ns/iter) │ +│ image-rs (wasm) │ 4,823,582 ns/iter (4,809,042..7,176,000 ns/iter) │ +│ imagescript-rs (wasm) │ 600,103 ns/iter (597,042..802,751 ns/iter) │ +└───────────────────────────────────────────────────────────────────────────────┘ + blur (5.0f/256x256) +┌─────────────────────────────────────────────────────────────────────────────────┐ +│ jimp │ 3,752,613 ns/iter (3,338,751..17,802,125 ns/iter) │ +│ imagescript │ 1,982,010 ns/iter (1,935,459..2,907,833 ns/iter) │ +│ sharp │ 36,079,515 ns/iter (2,465,000..210,155,512,001 ns/iter) │ +│ image-rs (wasm) │ 6,050,020 ns/iter (6,037,125..8,032,876 ns/iter) │ +│ imagescript-rs (wasm) │ 1,288,080 ns/iter (1,263,834..1,699,542 ns/iter) │ +└─────────────────────────────────────────────────────────────────────────────────┘ + blur (5.0f/1024x1024) +┌───────────────────────────────────────────────────────────────────────────────┐ +│ jimp │ 105,250,057 ns/iter (89,942,042..302,817,625 ns/iter) │ +│ imagescript │ 31,996,324 ns/iter (31,372,417..101,801,209 ns/iter) │ +│ sharp │ 20,019,663 ns/iter (18,547,168..66,675,542 ns/iter) │ +│ image-rs (wasm) │ 97,924,025 ns/iter (96,879,584..158,598,250 ns/iter) │ +│ imagescript-rs (wasm) │ 20,960,014 ns/iter (20,533,709..104,136,960 ns/iter) │ +└───────────────────────────────────────────────────────────────────────────────┘ +``` \ No newline at end of file diff --git a/bench/resize.mjs b/bench/resize.mjs new file mode 100644 index 0000000..2028ce7 --- /dev/null +++ b/bench/resize.mjs @@ -0,0 +1,52 @@ +import { sync, async, format } from './_.mjs'; + +import jimp from 'jimp'; +import sharp from 'sharp'; +import v2 from '../v2/framebuffer.mjs'; +import * as imagers from '@evan/wasm/target/image/node.mjs'; +import * as v2_wasm from '@evan/wasm/target/imagescript/node.mjs'; +const rgba = new Uint8Array(4 * 256 * 256).map((_, i) => i % 256); + +const images = { + v2: () => new v2(256, 256, rgba), + v2_wasm: v2_wasm.framebuffer.from(256, 256, rgba), + imagers: imagers.framebuffer.from(256, 256, rgba), + sharp: sharp(rgba, { raw: { width: 256, height: 256, channels: 4 } }), + jimp: await new Promise(r => new jimp({ width: 256, height: 256, data: rgba }, (_, i) => r(i))), +}; + +console.log(format({ + percentiles: false, + title: 'resize linear (256 -> 1024)', + + results: { + // others don't have linear + imagescript: sync(1e3, () => images.v2().resize('linear', 1024, 1024)), + 'imagescript-rs (wasm)': sync(1e3, () => v2_wasm.resize(images.v2_wasm, 'linear', 1024, 1024).drop()), + }, +})); + +console.log(format({ + percentiles: false, + title: 'resize cubic (256 -> 1024)', + + results: { + // others don't have cubic + imagescript: sync(1e3, () => images.v2().resize('cubic', 1024, 1024)), + sharp: await async(1e3, () => images.sharp.resize(1024, 1024, { kernel: 'cubic' }).toBuffer()), + 'imagescript-rs (wasm)': sync(1e3, () => v2_wasm.resize(images.v2_wasm, 'cubic', 1024, 1024).drop()), + }, +})); + +console.log(format({ + percentiles: false, + title: 'resize nearest (256 -> 1024)', + + results: { + imagescript: sync(1e4, () => images.v2().resize('nearest', 1024, 1024)), + jimp: sync(1e4, () => images.jimp.resize(1024, 1024, jimp.RESIZE_NEAREST_NEIGHBOR)), + sharp: await async(1e4, () => images.sharp.resize(1024, 1024, { kernel: 'nearest' }).toBuffer()), + 'image-rs (wasm)': sync(1e4, () => imagers.resize(images.imagers, 'nearest', 1024, 1024).drop()), + 'imagescript-rs (wasm)': sync(1e4, () => v2_wasm.resize(images.v2_wasm, 'nearest', 1024, 1024).drop()), + }, +})); \ No newline at end of file diff --git a/codecs/.npmignore b/codecs/.npmignore new file mode 100644 index 0000000..eb5b7ff --- /dev/null +++ b/codecs/.npmignore @@ -0,0 +1,2 @@ +src/ +test/ \ No newline at end of file diff --git a/codecs/LICENSE b/codecs/LICENSE new file mode 100644 index 0000000..c878a6c --- /dev/null +++ b/codecs/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021-present matmen, evanwashere + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/codecs/lib.d.ts b/codecs/lib.d.ts new file mode 100644 index 0000000..df9d05b --- /dev/null +++ b/codecs/lib.d.ts @@ -0,0 +1,50 @@ +declare module '@imagescript/codecs' { + type wah = { width: number, height: number }; + type jpeg_encode_options = wah & { quality?: number }; + type webp_encode_options = wah & { quality?: number }; + + type png_encode_options = wah & { + compression?: 'fast' | 'best' | 'default', + filter?: 'up' | 'sub' | 'none' | 'paeth' | 'average', + }; + + type gif_frame_options = wah & { + x?: number, + y?: number, + delay?: number, + speed?: number, + colors?: number, + quality?: number, + dispose?: 'any' | 'keep' | 'previous' | 'background', + } + + + class gif_encoder { + width: number; + height: number; + + constructor(width: number, height: number): this; + add(buffer: ArrayBufferView, options: gif_frame_options): void; + finish(options: { repeat?: number, comment: string, application?: string }): Uint8Array; + } + + + export interface gif { + encoder: gif_encoder, + } + + export interface png { + encode(buffer: ArrayBufferView, options: png_encode_options): Uint8Array, + encode_async(buffer: ArrayBufferView, options: png_encode_options): Promise, + } + + export interface jpeg { + encode(buffer: ArrayBufferView, options: png_encode_options): Uint8Array, + encode_async(buffer: ArrayBufferView, options: png_encode_options): Promise, + } + + export interface webp { + encode(buffer: ArrayBufferView, options: png_encode_options): Uint8Array, + encode_async(buffer: ArrayBufferView, options: png_encode_options): Promise, + } +} \ No newline at end of file diff --git a/codecs/lib.js b/codecs/lib.js new file mode 100644 index 0000000..38d0592 --- /dev/null +++ b/codecs/lib.js @@ -0,0 +1,6 @@ +let codecs; + +if (process.env.CODECS_FORCE_WASM) codecs = require('./wasm/index.js'); +else try { codecs = require('./node/index.js'); } catch { codecs = require('./wasm/index.js'); } + +throw new Error('todo!'); \ No newline at end of file diff --git a/codecs/lib.mjs b/codecs/lib.mjs new file mode 100644 index 0000000..e270c4a --- /dev/null +++ b/codecs/lib.mjs @@ -0,0 +1 @@ +import lib from './lib.js'; \ No newline at end of file diff --git a/codecs/node/bin/arm64-darwin.node b/codecs/node/bin/arm64-darwin.node new file mode 100755 index 0000000..b3d6509 Binary files /dev/null and b/codecs/node/bin/arm64-darwin.node differ diff --git a/node/arm64-linux.node b/codecs/node/bin/arm64-linux.node similarity index 100% rename from node/arm64-linux.node rename to codecs/node/bin/arm64-linux.node diff --git a/codecs/node/bin/x64-darwin.node b/codecs/node/bin/x64-darwin.node new file mode 100755 index 0000000..2a2e73c Binary files /dev/null and b/codecs/node/bin/x64-darwin.node differ diff --git a/node/x64-linux.node b/codecs/node/bin/x64-linux.node similarity index 100% rename from node/x64-linux.node rename to codecs/node/bin/x64-linux.node diff --git a/node/x64-win32.node b/codecs/node/bin/x64-win32.node similarity index 100% rename from node/x64-win32.node rename to codecs/node/bin/x64-win32.node diff --git a/codecs/node/index.js b/codecs/node/index.js new file mode 100644 index 0000000..af92a81 --- /dev/null +++ b/codecs/node/index.js @@ -0,0 +1,3 @@ +const { arch, platform } = require('os'); +try { module.exports = require(`./bin/${arch()}-${platform()}.node`); } +catch (err) { throw new Error('unsupported arch/platform: ' + err.message); } \ No newline at end of file diff --git a/codecs/node/index.mjs b/codecs/node/index.mjs new file mode 100644 index 0000000..698ce73 --- /dev/null +++ b/codecs/node/index.mjs @@ -0,0 +1,6 @@ +import lib from './index.js'; + +export const png = lib.png; +export const gif = lib.gif; +export const jpeg = lib.jpeg; +export const webp = lib.webp; \ No newline at end of file diff --git a/codecs/package.json b/codecs/package.json new file mode 100644 index 0000000..af14301 --- /dev/null +++ b/codecs/package.json @@ -0,0 +1,14 @@ +{ + "license": "MIT", + "main": "lib.js", + "version": "0.0.1", + "types": "lib.d.ts", + "name": "@imagescript/codecs", + "description": "fast codecs bindings for node and browsers", + "author": "imagescript (https://github.com/matmen/imagescript)", + "bugs": { "url": "https://github.com/matmen/imagescript/issues" }, + "homepage": "https://github.com/matmen/ImageScript/blob/master/codecs/readme.md", + "repository": { "type": "git", "url": "git+https://github.com/matmen/imagescript.git" }, + "exports": { ".": [{ "import": "./lib.mjs", "require": "./lib.js" }, "./lib.js"], "./*": "./*" }, + "keywords": ["png", "jpg", "gif", "jpeg", "webp", "fast", "wasm", "codecs", "native", "bindings"] +} \ No newline at end of file diff --git a/codecs/readme.md b/codecs/readme.md new file mode 100644 index 0000000..4e8a4aa --- /dev/null +++ b/codecs/readme.md @@ -0,0 +1,38 @@ +# fast codecs bindings for node and browsers + +`npm i @imagescript/codecs` + +```js +import { png } from '@imagescript/codecs'; + +const rgba = new Uint32Array(256 * 256); +const image = png.encode(rgba, { width: 256, height: 256 }); +``` + +## supported platforms +| | node@10 | node@12 | node@14 | node@16 | +| ---------------- | ------- | ------- | ------- | ------- | +| wasm32 | ✕ | ✕ | ✕ | ✕ | +| macos x64 | ✓ | ✓ | ✓ | ✓ | +| macos arm64 | ✓ | ✓ | ✓ | ✓ | +| windows x64 | ✓ | ✓ | ✓ | ✓ | +| linux x64 gnu | ✓ | ✓ | ✓ | ✓ | +| linux arm64 gnu | ✓ | ✓ | ✓ | ✓ | + +you can force usage of wasm by setting `CODECS_FORCE_WASM` env variable + +for deno and browsers use `@imagescript/codecs/wasm/bundle/browser.js` [cdn](https://unpkg.com/@imagescript/codecs/wasm/bundle/browser.js) + +## benchmarks + +image used for benchmarks: `new framebuffer(width, height).fill((x, y) => x * y)` + +![benchmark](https://plot.evan.lol/bar/eyJ0aXRsZSI6IkdJRiBvcHMvcyAoaGlnaGVyIGlzIGJldHRlcikiLCJwb2ludHMiOlt7Im5hbWUiOiJlbmNvZGUoNXggUkdCQSAyNTZ4MjU2KSIsInNjb3JlcyI6WzE0LjU2LDIuMzZdfSx7Im5hbWUiOiJlbmNvZGUoNXggUkdCQSAxMDI0eDEwMjQpIiwic2NvcmVzIjpbMC43MywwLjIxXX1dLCJsZWdlbmQiOlt7Im5hbWUiOiJuYXRpdmUoQGltYWdlc2NyaXB0L2NvZGVjcykiLCJjb2xvciI6ODUxMTM4MDQ3fSx7Im5hbWUiOiJqcyhAc2t5cmEvZ2lmZW5jKSIsImNvbG9yIjotMTI1MDk3MjY3M31dfQ==.png) + +![benchmark](https://plot.evan.lol/bar/eyJ0aXRsZSI6IkpQRUcgb3BzL3MgKGhpZ2hlciBpcyBiZXR0ZXIpIiwicG9pbnRzIjpbeyJuYW1lIjoiZW5jb2RlKFJHQkEgNjR4NjQpIiwic2NvcmVzIjpbNDMuNTgsNTcyOS4wOCw4MTEuMjldfSx7Im5hbWUiOiJlbmNvZGUoUkdCQSAyNTZ4MjU2KSIsInNjb3JlcyI6WzMyLjQ0LDM2NS45MywyMjguN119LHsibmFtZSI6ImVuY29kZShSR0JBIDUxMng1MTIpIiwic2NvcmVzIjpbMTYuMjIsODIuOTgsNzkuMjddfSx7Im5hbWUiOiJlbmNvZGUoUkdCQSAxMDI0eDEwMjQpIiwic2NvcmVzIjpbNC4yMiwxOS4xNiwyMi43OV19LHsibmFtZSI6ImVuY29kZShSR0JBIDIwNDh4MjA0OCkiLCJzY29yZXMiOlsxLjA1LDQuODksNS42N119XSwibGVnZW5kIjpbeyJuYW1lIjoianMoanBlZy1qcykiLCJjb2xvciI6ODUxMTM4MDQ3fSx7Im5hbWUiOiJuYXRpdmUoQGltYWdlc2NyaXB0L2NvZGVjcykiLCJjb2xvciI6LTEyNTA5NzI2NzN9LHsibmFtZSI6Im5hdGl2ZShzaGFycCkiLCJjb2xvciI6LTExNTY1MDA0ODF9XX0=.png) + +![benchmark](https://plot.evan.lol/bar/eyJ0aXRsZSI6IlBORyBvcHMvcyAoaGlnaGVyIGlzIGJldHRlcikiLCJwb2ludHMiOlt7Im5hbWUiOiJlbmNvZGUoUkdCQSA2NHg2NCkiLCJzY29yZXMiOlsyNDAuNzEsMTQzNy44Nyw2OTAuOTQsNzY2LjA1XX0seyJuYW1lIjoiZW5jb2RlKFJHQkEgMjU2eDI1NikiLCJzY29yZXMiOlsxMi43OSw1Ni4yOCwzMS41MywxMTIuNDZdfSx7Im5hbWUiOiJlbmNvZGUoUkdCQSA1MTJ4NTEyKSIsInNjb3JlcyI6WzkuOTQsMjUuODMsMTAuMzEsMzQuODZdfSx7Im5hbWUiOiJlbmNvZGUoUkdCQSAxMDI0eDEwMjQpIiwic2NvcmVzIjpbMy4wNCw3LDMuMzcsMTAuMzddfSx7Im5hbWUiOiJlbmNvZGUoUkdCQSAyMDQ4eDIwNDgpIiwic2NvcmVzIjpbMC44LDEuNzYsMC45NywyLjddfV0sImxlZ2VuZCI6W3sibmFtZSI6ImpzKHVwbmcpIiwiY29sb3IiOjg1MTEzODA0N30seyJuYW1lIjoibmF0aXZlKEBpbWFnZXNjcmlwdC9jb2RlY3MpIiwiY29sb3IiOi0xMjUwOTcyNjczfSx7Im5hbWUiOiJqcyhpbWFnZXNjcmlwdCkiLCJjb2xvciI6LTExNTY1MDA0ODF9LHsibmFtZSI6Im5hdGl2ZShzaGFycCkiLCJjb2xvciI6LTE0MTI4NzE2OX1dfQ==.png) + +## License + +MIT © [evan](https://github.com/evanwashere) [matmen](https://github.com/matmen) \ No newline at end of file diff --git a/wasm/simd.wasm b/codecs/tests/gif.js similarity index 100% rename from wasm/simd.wasm rename to codecs/tests/gif.js diff --git a/wasm/unknown.wasm b/codecs/tests/jpeg.js similarity index 100% rename from wasm/unknown.wasm rename to codecs/tests/jpeg.js diff --git a/codecs/tests/png.js b/codecs/tests/png.js new file mode 100644 index 0000000..e69de29 diff --git a/codecs/tests/results/gif/1024.nis.gif b/codecs/tests/results/gif/1024.nis.gif new file mode 100644 index 0000000..9466ffa Binary files /dev/null and b/codecs/tests/results/gif/1024.nis.gif differ diff --git a/codecs/tests/results/gif/1024.skyra.gif b/codecs/tests/results/gif/1024.skyra.gif new file mode 100644 index 0000000..de381e8 Binary files /dev/null and b/codecs/tests/results/gif/1024.skyra.gif differ diff --git a/codecs/tests/results/gif/256.nis.gif b/codecs/tests/results/gif/256.nis.gif new file mode 100644 index 0000000..9467854 Binary files /dev/null and b/codecs/tests/results/gif/256.nis.gif differ diff --git a/codecs/tests/results/gif/256.skyra.gif b/codecs/tests/results/gif/256.skyra.gif new file mode 100644 index 0000000..4e8ac9c Binary files /dev/null and b/codecs/tests/results/gif/256.skyra.gif differ diff --git a/codecs/tests/results/jpeg/256.jpegjs.jpeg b/codecs/tests/results/jpeg/256.jpegjs.jpeg new file mode 100644 index 0000000..7cd8f2b Binary files /dev/null and b/codecs/tests/results/jpeg/256.jpegjs.jpeg differ diff --git a/codecs/tests/results/jpeg/256.nis.jpeg b/codecs/tests/results/jpeg/256.nis.jpeg new file mode 100644 index 0000000..e6bb878 Binary files /dev/null and b/codecs/tests/results/jpeg/256.nis.jpeg differ diff --git a/codecs/tests/results/jpeg/256.sharp.jpeg b/codecs/tests/results/jpeg/256.sharp.jpeg new file mode 100644 index 0000000..d57978c Binary files /dev/null and b/codecs/tests/results/jpeg/256.sharp.jpeg differ diff --git a/codecs/tests/results/jpeg/512.jpegjs.jpeg b/codecs/tests/results/jpeg/512.jpegjs.jpeg new file mode 100644 index 0000000..e87be33 Binary files /dev/null and b/codecs/tests/results/jpeg/512.jpegjs.jpeg differ diff --git a/codecs/tests/results/jpeg/512.nis.jpeg b/codecs/tests/results/jpeg/512.nis.jpeg new file mode 100644 index 0000000..5f52078 Binary files /dev/null and b/codecs/tests/results/jpeg/512.nis.jpeg differ diff --git a/codecs/tests/results/jpeg/512.sharp.jpeg b/codecs/tests/results/jpeg/512.sharp.jpeg new file mode 100644 index 0000000..9a2c269 Binary files /dev/null and b/codecs/tests/results/jpeg/512.sharp.jpeg differ diff --git a/codecs/tests/results/jpeg/64.jpegjs.jpeg b/codecs/tests/results/jpeg/64.jpegjs.jpeg new file mode 100644 index 0000000..a3910bb Binary files /dev/null and b/codecs/tests/results/jpeg/64.jpegjs.jpeg differ diff --git a/codecs/tests/results/jpeg/64.nis.jpeg b/codecs/tests/results/jpeg/64.nis.jpeg new file mode 100644 index 0000000..9eb85c9 Binary files /dev/null and b/codecs/tests/results/jpeg/64.nis.jpeg differ diff --git a/codecs/tests/results/jpeg/64.sharp.jpeg b/codecs/tests/results/jpeg/64.sharp.jpeg new file mode 100644 index 0000000..e275b71 Binary files /dev/null and b/codecs/tests/results/jpeg/64.sharp.jpeg differ diff --git a/codecs/tests/results/png/256.jis.png b/codecs/tests/results/png/256.jis.png new file mode 100644 index 0000000..74358f7 Binary files /dev/null and b/codecs/tests/results/png/256.jis.png differ diff --git a/codecs/tests/results/png/256.nis.png b/codecs/tests/results/png/256.nis.png new file mode 100644 index 0000000..f9cf386 Binary files /dev/null and b/codecs/tests/results/png/256.nis.png differ diff --git a/codecs/tests/results/png/256.sharp.png b/codecs/tests/results/png/256.sharp.png new file mode 100644 index 0000000..7beee04 Binary files /dev/null and b/codecs/tests/results/png/256.sharp.png differ diff --git a/codecs/tests/results/png/256.upng.png b/codecs/tests/results/png/256.upng.png new file mode 100644 index 0000000..8009676 Binary files /dev/null and b/codecs/tests/results/png/256.upng.png differ diff --git a/codecs/tests/results/png/512.jis.png b/codecs/tests/results/png/512.jis.png new file mode 100644 index 0000000..5589be9 Binary files /dev/null and b/codecs/tests/results/png/512.jis.png differ diff --git a/codecs/tests/results/png/512.nis.png b/codecs/tests/results/png/512.nis.png new file mode 100644 index 0000000..76da3c4 Binary files /dev/null and b/codecs/tests/results/png/512.nis.png differ diff --git a/codecs/tests/results/png/512.sharp.png b/codecs/tests/results/png/512.sharp.png new file mode 100644 index 0000000..c1cf863 Binary files /dev/null and b/codecs/tests/results/png/512.sharp.png differ diff --git a/codecs/tests/results/png/512.upng.png b/codecs/tests/results/png/512.upng.png new file mode 100644 index 0000000..72c7d39 Binary files /dev/null and b/codecs/tests/results/png/512.upng.png differ diff --git a/codecs/tests/results/png/64.jis.png b/codecs/tests/results/png/64.jis.png new file mode 100644 index 0000000..69f1c7d Binary files /dev/null and b/codecs/tests/results/png/64.jis.png differ diff --git a/codecs/tests/results/png/64.nis.png b/codecs/tests/results/png/64.nis.png new file mode 100644 index 0000000..fb82edd Binary files /dev/null and b/codecs/tests/results/png/64.nis.png differ diff --git a/codecs/tests/results/png/64.sharp.png b/codecs/tests/results/png/64.sharp.png new file mode 100644 index 0000000..72066d2 Binary files /dev/null and b/codecs/tests/results/png/64.sharp.png differ diff --git a/codecs/tests/results/png/64.upng.png b/codecs/tests/results/png/64.upng.png new file mode 100644 index 0000000..12b64c1 Binary files /dev/null and b/codecs/tests/results/png/64.upng.png differ diff --git a/codecs/tests/webp.js b/codecs/tests/webp.js new file mode 100644 index 0000000..e69de29 diff --git a/codecs/wasm/bin/codecs.wasm b/codecs/wasm/bin/codecs.wasm new file mode 100644 index 0000000..e69de29 diff --git a/codecs/wasm/bin/simd.wasm b/codecs/wasm/bin/simd.wasm new file mode 100644 index 0000000..e69de29 diff --git a/codecs/wasm/bundle/browser.js b/codecs/wasm/bundle/browser.js new file mode 100644 index 0000000..dd71b68 --- /dev/null +++ b/codecs/wasm/bundle/browser.js @@ -0,0 +1 @@ +throw new Error('todo!'); \ No newline at end of file diff --git a/codecs/wasm/index.js b/codecs/wasm/index.js new file mode 100644 index 0000000..dd71b68 --- /dev/null +++ b/codecs/wasm/index.js @@ -0,0 +1 @@ +throw new Error('todo!'); \ No newline at end of file diff --git a/codecs/wasm/index.mjs b/codecs/wasm/index.mjs new file mode 100644 index 0000000..1a58364 --- /dev/null +++ b/codecs/wasm/index.mjs @@ -0,0 +1 @@ +import lib from './index.js'; \ No newline at end of file diff --git a/node/arm64-darwin.node b/node/arm64-darwin.node deleted file mode 100755 index 680fe23..0000000 Binary files a/node/arm64-darwin.node and /dev/null differ diff --git a/node/index.js b/node/index.js deleted file mode 100644 index b6ac5ff..0000000 --- a/node/index.js +++ /dev/null @@ -1,7 +0,0 @@ -const { arch, platform } = require('os'); - -try { - module.exports = require(`./${arch()}-${platform()}.node`); -} catch (err) { - throw new Error('unsupported arch/platform: ' + err.message); -} \ No newline at end of file diff --git a/node/x64-darwin.node b/node/x64-darwin.node deleted file mode 100755 index 30d7215..0000000 Binary files a/node/x64-darwin.node and /dev/null differ diff --git a/package.json b/package.json index 8de1a3a..bc332b3 100644 --- a/package.json +++ b/package.json @@ -1,8 +1,9 @@ { "name": "imagescript", - "version": "1.2.7", + "version": "1.3.1", "description": "zero-dependency javascript image manipulation", "main": "ImageScript.js", + "types": "ImageScript.d.ts", "scripts": { "test": "node ./tests/run.js", "coverage": "nyc --reporter=html npm test" @@ -14,10 +15,22 @@ "keywords": [ "image", "image processing", - "image manipulation" + "image manipulation", + "png", + "jpeg", + "jpg", + "scale", + "resize", + "crop", + "webp", + "svg", + "bitmap", + "gif", + "picture", + "thumbnail" ], - "author": "matmen ", - "license": "GPL-3.0-or-later", + "author": "Mathis Mensing ", + "license": "(AGPL-3.0-or-later OR MIT)", "bugs": { "url": "https://github.com/matmen/ImageScript/issues" }, diff --git a/png/README.md b/png/README.md index e69de29..2fd9f95 100644 --- a/png/README.md +++ b/png/README.md @@ -0,0 +1 @@ +TBD \ No newline at end of file diff --git a/png/src/crc.js b/png/src/crc.mjs similarity index 100% rename from png/src/crc.js rename to png/src/crc.mjs diff --git a/png/src/mem.js b/png/src/mem.mjs similarity index 100% rename from png/src/mem.js rename to png/src/mem.mjs diff --git a/png/src/png.js b/png/src/png.mjs similarity index 98% rename from png/src/png.js rename to png/src/png.mjs index be8beb0..62848d4 100644 --- a/png/src/png.js +++ b/png/src/png.mjs @@ -1,6 +1,6 @@ -import { crc32 } from './crc.js'; -import { from_parts } from './mem.js'; -import { compress, decompress } from './zlib.js'; +import { crc32 } from './crc.mjs'; +import { from_parts } from './mem.mjs'; +import { compress, decompress } from './zlib.mjs'; const __IHDR__ = new Uint8Array([73, 72, 68, 82]); const __IDAT__ = new Uint8Array([73, 68, 65, 84]); diff --git a/png/src/zlib.js b/png/src/zlib.mjs similarity index 100% rename from png/src/zlib.js rename to png/src/zlib.mjs diff --git a/tests/flip.js b/tests/flip.js new file mode 100644 index 0000000..9fe22d3 --- /dev/null +++ b/tests/flip.js @@ -0,0 +1,36 @@ +const fs = require('fs').promises; +const {Image} = require('../ImageScript'); + +(async () => { + const input = await fs.readFile('./tests/targets/external.png'); + + { + const image = await Image.decode(input); + image.flip('horizontal'); + + const output = await image.encode(1, {creationTime: 0, software: ''}); + + if (process.env.OVERWRITE_TEST) + await fs.writeFile('./tests/targets/flip-horizontal.png', output); + + const target = await fs.readFile('./tests/targets/flip-horizontal.png'); + + if (!Buffer.from(target).equals(Buffer.from(output))) + process.exit(1); + } + + { + const image = await Image.decode(input); + image.flip('vertical'); + + const output = await image.encode(1, {creationTime: 0, software: ''}); + + if (process.env.OVERWRITE_TEST) + await fs.writeFile('./tests/targets/flip-vertical.png', output); + + const target = await fs.readFile('./tests/targets/flip-vertical.png'); + + if (!Buffer.from(target).equals(Buffer.from(output))) + process.exit(1); + } +})(); diff --git a/tests/font.js b/tests/font.js index f14909d..f06b175 100644 --- a/tests/font.js +++ b/tests/font.js @@ -34,4 +34,15 @@ const panic = message => { const desired = await fs.readFile('./tests/targets/font-2.png'); if (!desired.equals(Buffer.from(encoded))) panic('font 2 doesn\'t match'); } + + { + const font = await Image.renderText(await fs.readFile('./tests/fonts/opensans bold.ttf'), 128, 'Extra\n-Test\nnewline'); + const encoded = await font.encode(1, {creationTime: 0, software: ''}); + + if (process.env.OVERWRITE_TEST) + await fs.writeFile('./tests/targets/font-3.png', encoded); + + const desired = await fs.readFile('./tests/targets/font-3.png'); + if (!desired.equals(Buffer.from(encoded))) panic('font 3 doesn\'t match'); + } })(); diff --git a/tests/fonts/big.ttf b/tests/fonts/big.ttf new file mode 100644 index 0000000..78f39a6 Binary files /dev/null and b/tests/fonts/big.ttf differ diff --git a/tests/fonts/opensans bold.ttf b/tests/fonts/opensans bold.ttf new file mode 100644 index 0000000..7b52945 Binary files /dev/null and b/tests/fonts/opensans bold.ttf differ diff --git a/tests/rotate.js b/tests/rotate.js index c0a8089..2a49cb3 100644 --- a/tests/rotate.js +++ b/tests/rotate.js @@ -35,6 +35,21 @@ const panic = msg => { if (!Buffer.from(target).equals(Buffer.from(encoded))) panic('rotate 45 noresize failed'); } + { + const binary = await fs.readFile('./tests/targets/image.png'); + const image = await Image.decode(binary); + image.rotate(90); + + const encoded = await image.encode(1, {creationTime: 0, software: ''}); + + if (process.env.OVERWRITE_TEST) + await fs.writeFile('./tests/targets/rotate-90.png', encoded); + + await fs.writeFile('./tests/targets/rotate-90.png', encoded); + const target = await fs.readFile('./tests/targets/rotate-90.png'); + if (!Buffer.from(target).equals(Buffer.from(encoded))) panic('rotate 90 failed'); + } + { const binary = await fs.readFile('./tests/targets/image.png'); const image = await Image.decode(binary); @@ -50,6 +65,21 @@ const panic = msg => { if (!Buffer.from(target).equals(Buffer.from(encoded))) panic('rotate 180 failed'); } + { + const binary = await fs.readFile('./tests/targets/image.png'); + const image = await Image.decode(binary); + image.rotate(270); + + const encoded = await image.encode(1, {creationTime: 0, software: ''}); + + if (process.env.OVERWRITE_TEST) + await fs.writeFile('./tests/targets/rotate-270.png', encoded); + + await fs.writeFile('./tests/targets/rotate-270.png', encoded); + const target = await fs.readFile('./tests/targets/rotate-270.png'); + if (!Buffer.from(target).equals(Buffer.from(encoded))) panic('rotate 270 failed'); + } + { const image = new Image(512, 512); image.fill((x) => Image.hslToColor(x / image.width, 1, .5)); diff --git a/tests/targets/circle3.png b/tests/targets/circle3.png index a8316ff..27bb41d 100644 Binary files a/tests/targets/circle3.png and b/tests/targets/circle3.png differ diff --git a/tests/targets/circle4.png b/tests/targets/circle4.png index dbf07ef..00b15ad 100644 Binary files a/tests/targets/circle4.png and b/tests/targets/circle4.png differ diff --git a/tests/targets/flip-horizontal.png b/tests/targets/flip-horizontal.png new file mode 100644 index 0000000..432046f Binary files /dev/null and b/tests/targets/flip-horizontal.png differ diff --git a/tests/targets/flip-vertical.png b/tests/targets/flip-vertical.png new file mode 100644 index 0000000..29262e3 Binary files /dev/null and b/tests/targets/flip-vertical.png differ diff --git a/tests/targets/font-1.png b/tests/targets/font-1.png index 8be28c9..a3360ca 100644 Binary files a/tests/targets/font-1.png and b/tests/targets/font-1.png differ diff --git a/tests/targets/font-2.png b/tests/targets/font-2.png index fff6d52..f4b5d1a 100644 Binary files a/tests/targets/font-2.png and b/tests/targets/font-2.png differ diff --git a/tests/targets/font-3.png b/tests/targets/font-3.png new file mode 100644 index 0000000..8ca1c35 Binary files /dev/null and b/tests/targets/font-3.png differ diff --git a/tests/targets/readme.png b/tests/targets/readme.png index 88bbdee..899b561 100644 Binary files a/tests/targets/readme.png and b/tests/targets/readme.png differ diff --git a/tests/targets/rotate-270.png b/tests/targets/rotate-270.png new file mode 100644 index 0000000..e3e32f0 Binary files /dev/null and b/tests/targets/rotate-270.png differ diff --git a/tests/targets/rotate-45-noresize.png b/tests/targets/rotate-45-noresize.png index 9a0e751..0b58327 100644 Binary files a/tests/targets/rotate-45-noresize.png and b/tests/targets/rotate-45-noresize.png differ diff --git a/tests/targets/rotate-45.png b/tests/targets/rotate-45.png index fb03538..2e63c5c 100644 Binary files a/tests/targets/rotate-45.png and b/tests/targets/rotate-45.png differ diff --git a/tests/targets/rotate-90.png b/tests/targets/rotate-90.png new file mode 100644 index 0000000..9754ef2 Binary files /dev/null and b/tests/targets/rotate-90.png differ diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..1312e9a --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "target": "es6", + "module": "commonjs", + "strict": true, + "noImplicitAny": true, + "strictNullChecks": true, + "noImplicitThis": true, + "alwaysStrict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noImplicitReturns": true, + "noFallthroughCasesInSwitch": true, + "moduleResolution": "node", + "allowJs": true, + "allowSyntheticDefaultImports": true, + "skipLibCheck": true, + "lib": ["es6"] + }, + "files": ["ImageScript.d.ts"] +} diff --git a/v2/codecs/magic.js b/v2/codecs/magic.js index adbbdc7..a31f6ca 100644 --- a/v2/codecs/magic.js +++ b/v2/codecs/magic.js @@ -1,4 +1,4 @@ -const { view } = require('../util/mem.js'); +const { view } = require('../../utils/mem.js'); const formats = { ttf: { type: 'font', format: 'ttf' }, diff --git a/v2/framebuffer.js b/v2/framebuffer.js index 37722d2..bd8db09 100644 --- a/v2/framebuffer.js +++ b/v2/framebuffer.js @@ -1,69 +1,22 @@ -var __create = Object.create; var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; var __markAsModule = (target) => __defProp(target, "__esModule", { value: true }); -var __commonJS = (cb, mod) => function __require() { - return mod || (0, cb[Object.keys(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; -}; var __export = (target, all) => { + __markAsModule(target); for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; -var __reExport = (target, module2, desc) => { - if (module2 && typeof module2 === "object" || typeof module2 === "function") { - for (let key of __getOwnPropNames(module2)) - if (!__hasOwnProp.call(target, key) && key !== "default") - __defProp(target, key, { get: () => module2[key], enumerable: !(desc = __getOwnPropDesc(module2, key)) || desc.enumerable }); - } - return target; -}; -var __toModule = (module2) => { - return __reExport(__markAsModule(__defProp(module2 != null ? __create(__getProtoOf(module2)) : {}, "default", module2 && module2.__esModule && "default" in module2 ? { get: () => module2.default, enumerable: true } : { value: module2, enumerable: true })), module2); -}; - -// v2/util/mem.js -var require_mem = __commonJS({ - "v2/util/mem.js"(exports, module2) { - function view3(buffer, shared = false) { - if (buffer instanceof ArrayBuffer) - return new Uint8Array(buffer); - if (shared && buffer instanceof SharedArrayBuffer) - return new Uint8Array(buffer); - if (ArrayBuffer.isView(buffer)) - return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength); - throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'"); - } - function from_parts2(buffers, shared = false) { - let length = 0; - let offset = 0; - buffers.forEach((buffer) => length += buffer.byteLength == null ? buffer.length : buffer.byteLength); - const u82 = new Uint8Array(shared ? new SharedArrayBuffer(length) : length); - buffers.forEach((buffer) => { - const ref = Array.isArray(buffer) ? buffer : view3(buffer, true); - u82.set(ref, offset); - offset += ref.length; - }); - return u82; - } - module2.exports = { view: view3, from_parts: from_parts2 }; - } -}); // v2/framebuffer.mjs -__markAsModule(exports); __export(exports, { - Color: () => color_default, - default: () => framebuffer_default + Color: () => color, + default: () => framebuffer }); // v2/ops/color.js var color_exports = {}; __export(color_exports, { blend: () => blend, - default: () => color_default, + default: () => color, from_rgba: () => from_rgba, parse: () => parse, to_rgba: () => to_rgba @@ -188,7 +141,6 @@ var color = class { return this.value.toString(); } }; -var color_default = color; var colors = new Map([ ["aliceblue", 4042850303], ["antiquewhite", 4209760255], @@ -341,8 +293,16 @@ var colors = new Map([ ["yellowgreen", 2597139199] ]); -// v2/framebuffer.mjs -var import_mem2 = __toModule(require_mem()); +// v2/util/mem.js +function view(buffer, shared = false) { + if (buffer instanceof ArrayBuffer) + return new Uint8Array(buffer); + if (shared && buffer instanceof SharedArrayBuffer) + return new Uint8Array(buffer); + if (ArrayBuffer.isView(buffer)) + return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength); + throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'"); +} // v2/ops/flip.js var flip_exports = {}; @@ -365,8 +325,8 @@ function vertical(framebuffer2) { const oheight = framebuffer2.height | 0; const height = framebuffer2.height / 2 | 0; for (let y = 0 | 0; y < height; y++) { - const yo = y * width; - const wo1y = width * (oheight - 1 - y); + const yo = y * width | 0; + const wo1y = width * (oheight - 1 - y) | 0; for (let x2 = 0 | 0; x2 < width; x2++) { const offset = x2 + yo; const offset2 = x2 + wo1y; @@ -452,10 +412,12 @@ function gaussian(radius, framebuffer2) { const a1 = k * g1 * (a - 1); const a2 = k * g1 * (a + 1); const lc2 = (k + a1) / (1 - b1 - b2); + const width = framebuffer2.width | 0; const rc = (a2 + a3) / (1 - b1 - b2); - const tmp = new Float32Array(4 * Math.max(framebuffer2.width, framebuffer2.height)); - gc(old, framebuffer2.u8, tmp, framebuffer2.width, framebuffer2.height, k, a1, a2, a3, b1, b2, lc2, rc); - gc(framebuffer2.u8, old, tmp, framebuffer2.height, framebuffer2.width, k, a1, a2, a3, b1, b2, lc2, rc); + const height = framebuffer2.height | 0; + const tmp = new Float32Array(4 * Math.max(width, height)); + gc(old, framebuffer2.u8, tmp, width, height, k, a1, a2, a3, b1, b2, lc2, rc); + gc(framebuffer2.u8, old, tmp, height, width, k, a1, a2, a3, b1, b2, lc2, rc); } function bb(u82, old, width, height, radius) { const divisor = 1 / (1 + radius + radius); @@ -698,20 +660,32 @@ __export(crop_exports, { crop: () => crop, cut: () => cut }); +function clamp2(min, int, max2) { + const t = int < min ? min : int; + return t > max2 ? max2 : t; +} function cut(x2, y, width, height, framebuffer2) { + width |= 0; + height |= 0; const frame = new framebuffer2.constructor(width, height); - for (let yy = 0; yy < height; yy++) { - const offset = x2 + (y + yy) * framebuffer2.width; - frame.u32.set(framebuffer2.u32.subarray(offset, width + offset), yy * width); + const n32 = frame.u32; + const o32 = framebuffer2.u32; + const fwidth = framebuffer2.width | 0; + for (let yy = 0 | 0; yy < height; yy++) { + const offset = x2 + fwidth * (y + yy); + n32.set(o32.subarray(offset, width + offset), yy * width); } return frame; } function crop(x2, y, width, height, framebuffer2) { + width |= 0; + height |= 0; const old = framebuffer2.u32; - framebuffer2.u32 = new Uint32Array(width * height); + const fwidth = framebuffer2.width | 0; + const u323 = framebuffer2.u32 = new Uint32Array(width * height); for (let yy = 0; yy < height; yy++) { - const offset = x2 + (y + yy) * framebuffer2.width; - framebuffer2.u32.set(old.subarray(offset, width + offset), yy * width); + const offset = x2 + fwidth * (y + yy); + u323.set(old.subarray(offset, width + offset), yy * width); } framebuffer2.width = width; framebuffer2.height = height; @@ -719,21 +693,24 @@ function crop(x2, y, width, height, framebuffer2) { framebuffer2.view = new DataView(framebuffer2.u32.buffer); } function circle(feathering, framebuffer2) { - const rad = Math.min(framebuffer2.width, framebuffer2.height) / 2; + const u82 = framebuffer2.u8; + const u323 = framebuffer2.u32; + const width = framebuffer2.width | 0; + const height = framebuffer2.height | 0; + const rad = Math.min(width, height) / 2; + const cx = width / 2; + const cy = height / 2; const rad_2 = rad ** 2; - const cx = framebuffer2.width / 2; - const cy = framebuffer2.height / 2; const feathering_12 = feathering ** (1 / 2); - for (let y = 0; y < framebuffer2.height; y++) { + for (let y = 0 | 0; y < height; y++) { const cdy = (y - cy) ** 2; - const y_offset = y * framebuffer2.width; - for (let x2 = 0; x2 < framebuffer2.width; x2++) { + const y_offset = y * width; + for (let x2 = 0 | 0; x2 < width; x2++) { const cd = cdy + (x2 - cx) ** 2; - const offset = 3 + 4 * (x2 + y_offset); if (cd > rad_2) - framebuffer2.u8[offset] = 0; + u323[x2 + y_offset] = 0; else if (feathering) - framebuffer2.u8[offset] *= Math.max(0, Math.min(1, 1 - cd / rad_2 * feathering_12)); + u82[3 + 4 * (x2 + y_offset)] *= clamp2(0, 1 - cd / rad_2 * feathering_12, 1); } } return framebuffer2; @@ -749,17 +726,17 @@ __export(resize_exports, { function lerp(a, b, t) { return t * b + a * (1 - t); } -function clamp2(min, int, max2) { +function clamp3(min, int, max2) { const t = int < min ? min : int; return t > max2 ? max2 : t; } function clamped(x2, y, width, height) { - return 4 * (clamp2(0, x2, width - 1) + clamp2(0, y, height - 1) * width); + return 4 * (clamp3(0, x2, width - 1) + clamp3(0, y, height - 1) * width); } function hermite(A, B, C, D, t) { - const c = C / 2 + -A / 2; - const b = A + 2 * C - D / 2 - 5 * B / 2; - const a = D / 2 + -A / 2 + 3 * B / 2 - 3 * C / 2; + const c = C / 2 + A / -2; + const b = A + C * 2 - D / 2 - B * 2.5; + const a = D / 2 + A / -2 + B * 1.5 - C * 1.5; const t2 = t * t; return B + c * t + b * t2 + a * t * t2; } @@ -917,9 +894,10 @@ function rotate270(framebuffer2) { framebuffer2.width = height; framebuffer2.height = width; for (let y = 0 | 0; y < width; y++) { - const yoffset = y * width; + const yoffset = y * width | 0; + const soffset = y + width * (width - 1) | 0; for (let x2 = 0 | 0; x2 < height; x2++) { - u323[y + width * (width - 1 - x2)] = old[x2 + yoffset]; + u323[soffset - x2 * width] = old[x2 + yoffset]; } } } @@ -957,12 +935,7 @@ function interpolate(inn, out, x0, y0, x1, y1) { const xq = x1 - x2; const yq = y1 - y2; const offset = 4 * (x0 + y0 * out.width); - const ref = { - r: 0, - g: 0, - b: 0, - a: 0 - }; + const ref = { r: 0, g: 0, b: 0, a: 0 }; pawn(x2, y2, (1 - xq) * (1 - yq), ref, inn); pawn(1 + x2, y2, xq * (1 - yq), ref, inn); pawn(x2, 1 + y2, (1 - xq) * yq, ref, inn); @@ -986,56 +959,64 @@ function pawn(point0, point1, weight, ref, inn) { // v2/ops/overlay.js var overlay_exports = {}; __export(overlay_exports, { - overlay: () => overlay, + blend: () => blend2, replace: () => replace }); function replace(bg, fg, x2, y) { - for (let yy = 0; yy < fg.height; yy++) { - let y_offset = y + yy; - if (y_offset < 0) - continue; - if (y_offset >= bg.height) - break; - for (let xx = 0; xx < fg.width; xx++) { - let x_offset = x2 + xx; - if (x_offset < 0) - continue; - if (x_offset >= bg.width) - break; - bg.u32[x_offset + y_offset * bg.width] = fg.u32[xx + yy * fg.width]; - } + const b32 = bg.u32; + const f32 = fg.u32; + const fw = fg.width | 0; + const bw = bg.width | 0; + const fh = fg.height | 0; + const bh = bg.height | 0; + const ox = (x2 > 0 ? 0 : -x2) | 0; + const oy = (y > 0 ? 0 : -y) | 0; + const top = (y > 0 ? y : 0) | 0; + const left = (x2 > 0 ? x2 : 0) | 0; + const width = Math.min(bw, x2 + fw) - left | 0; + const height = Math.min(bh, y + fh) - top | 0; + if (0 >= width || 0 >= height) + return; + for (let yy = 0 | 0; yy < height; yy++) { + const yyoffset = ox + fw * (yy + oy); + const yoffset = left + bw * (yy + top); + b32.subarray(yoffset, width + yoffset).set(f32.subarray(yyoffset, width + yyoffset)); } } -function overlay(background, foreground, x2, y) { - x2 = x2 | 0; - y = y | 0; - const fwidth = foreground.width | 0; - const bwidth = background.width | 0; - const fheight = foreground.height | 0; - const bheight = background.height | 0; - for (let yy = 0 | 0; yy < fheight; yy++) { - let yoffset = y + yy; - if (yoffset < 0) - continue; - if (yoffset >= bheight) - break; - yoffset = bwidth * yoffset; - const yyoffset = yy * fwidth; - for (let xx = 0 | 0; xx < fwidth; xx++) { - let xoffset = x2 + xx; - if (xoffset < 0) +function blend2(bg, fg, x2, y) { + const b32 = bg.u32; + const f32 = fg.u32; + const fw = fg.width | 0; + const bw = bg.width | 0; + const fh = fg.height | 0; + const bh = bg.height | 0; + const ox = (x2 > 0 ? 0 : -x2) | 0; + const oy = (y > 0 ? 0 : -y) | 0; + const top = (y > 0 ? y : 0) | 0; + const left = (x2 > 0 ? x2 : 0) | 0; + const width = Math.min(bw, x2 + fw) - left | 0; + const height = Math.min(bh, y + fh) - top | 0; + if (0 >= width || 0 >= height) + return; + for (let yy = 0 | 0; yy < height; yy++) { + const yyoffset = ox + fw * (yy + oy); + const yoffset = left + bw * (yy + top); + for (let xx = 0 | 0; xx < width; xx++) { + const F = f32[xx + yyoffset]; + const fa = F >> 24 & 255; + if (fa === 0) continue; - if (xoffset >= bwidth) - break; - const offset = 4 * (xoffset + yoffset); - const fg = foreground.view.getUint32(4 * (xx + yyoffset), false); - const bg = background.view.getUint32(offset, false); - if ((fg & 255) === 255) - background.view.setUint32(offset, fg, false); - else if ((fg & 255) === 0) - background.view.setUint32(offset, bg, false); - else - background.view.setUint32(offset, blend(fg, bg), false); + else if (fa === 255) + b32[xx + yoffset] = F; + else { + const alpha = 1 + fa; + const inv_alpha = 256 - fa; + const B = b32[xx + yoffset]; + const r = alpha * (F & 255) + inv_alpha * (B & 255) >> 8; + const g = alpha * (F >> 8 & 255) + inv_alpha * (B >> 8 & 255) >> 8; + const b = alpha * (F >> 16 & 255) + inv_alpha * (B >> 16 & 255) >> 8; + b32[xx + yoffset] = Math.max(fa, B >> 24 & 255) << 24 | (b & 255) << 16 | (g & 255) << 8 | r; + } } } } @@ -1050,8 +1031,8 @@ __export(iterator_exports, { function* cords(framebuffer2) { const width = framebuffer2.width | 0; const height = framebuffer2.height | 0; - for (let y = 1 | 0; y <= height; y++) { - for (let x2 = 1 | 0; x2 <= width; x2++) + for (let y = 0 | 0; y < height; y++) { + for (let x2 = 0 | 0; x2 < width; x2++) yield [x2, y]; } } @@ -1060,8 +1041,8 @@ function* rgba(framebuffer2) { const u82 = framebuffer2.u8; const width = framebuffer2.width | 0; const height = framebuffer2.height | 0; - for (let y = 1 | 0; y <= height; y++) { - for (let x2 = 1 | 0; x2 <= width; x2++) { + for (let y = 0 | 0; y < height; y++) { + for (let x2 = 0 | 0; x2 < width; x2++) { yield [x2, y, u82.subarray(offset, offset += 4)]; } } @@ -1071,8 +1052,8 @@ function* u32(framebuffer2) { const view3 = framebuffer2.view; const width = framebuffer2.width | 0; const height = framebuffer2.height | 0; - for (let y = 1 | 0; y <= height; y++) { - for (let x2 = 1 | 0; x2 <= width; x2++) { + for (let y = 0 | 0; y < height; y++) { + for (let x2 = 0 | 0; x2 < width; x2++) { yield [x2, y, view3.getUint32(offset, false)]; offset += 4; } @@ -1355,7 +1336,7 @@ function crc32(buffer) { } // png/src/mem.js -function view(buffer, shared = false) { +function view2(buffer, shared = false) { if (buffer instanceof ArrayBuffer) return new Uint8Array(buffer); if (shared && buffer instanceof SharedArrayBuffer) @@ -1370,7 +1351,7 @@ function from_parts(buffers, shared = false) { buffers.forEach((buffer) => length += buffer.byteLength == null ? buffer.length : buffer.byteLength); const u82 = new Uint8Array(shared ? new SharedArrayBuffer(length) : length); buffers.forEach((buffer) => { - const ref = Array.isArray(buffer) ? buffer : view(buffer, true); + const ref = Array.isArray(buffer) ? buffer : view2(buffer, true); u82.set(ref, offset); offset += ref.length; }); @@ -1405,12 +1386,13 @@ var _b = freb(fdeb, 0); var fd = _b[0]; var revfd = _b[1]; var rev = new u16(32768); -for (var i = 0; i < 32768; ++i) { +for (i = 0; i < 32768; ++i) { x = (i & 43690) >>> 1 | (i & 21845) << 1; x = (x & 52428) >>> 2 | (x & 13107) << 2; x = (x & 61680) >>> 4 | (x & 3855) << 4; rev[i] = ((x & 65280) >>> 8 | (x & 255) << 8) >>> 1; } +var i; var x; var hMap = function(cd, mb, r) { var s = cd.length; @@ -1447,17 +1429,22 @@ var hMap = function(cd, mb, r) { return co; }; var flt = new u8(288); -for (var i = 0; i < 144; ++i) +for (i = 0; i < 144; ++i) flt[i] = 8; -for (var i = 144; i < 256; ++i) +var i; +for (i = 144; i < 256; ++i) flt[i] = 9; -for (var i = 256; i < 280; ++i) +var i; +for (i = 256; i < 280; ++i) flt[i] = 7; -for (var i = 280; i < 288; ++i) +var i; +for (i = 280; i < 288; ++i) flt[i] = 8; +var i; var fdt = new u8(32); -for (var i = 0; i < 32; ++i) +for (i = 0; i < 32; ++i) fdt[i] = 5; +var i; var flm = hMap(flt, 9, 0); var flrm = hMap(flt, 9, 1); var fdm = hMap(fdt, 5, 0); @@ -2208,11 +2195,11 @@ var framebuffer = class { constructor(width, height, buffer) { this.width = width | 0; this.height = height | 0; - this.u8 = buffer ? (0, import_mem2.view)(buffer) : new Uint8Array(4 * this.width * this.height); + this.u8 = buffer ? view(buffer) : new Uint8Array(4 * this.width * this.height); this.view = new DataView(this.u8.buffer, this.u8.byteOffset, this.u8.byteLength); this.u32 = new Uint32Array(this.u8.buffer, this.u8.byteOffset, this.u8.byteLength / 4); if (this.u8.length !== 4 * this.width * this.height) - throw new TypeError("invalid capacity of buffer"); + throw new RangeError("invalid capacity of buffer"); } [Symbol.iterator]() { return iterator_exports.cords(this); @@ -2220,29 +2207,29 @@ var framebuffer = class { toString() { return `framebuffer<${this.width}x${this.height}>`; } + get(x2, y) { + return this.view.getUint32((x2 | 0) + (y | 0) * this.width, false); + } clone() { return new this.constructor(this.width, this.height, this.u8.slice()); } + set(x2, y, color3) { + this.view.setUint32((x2 | 0) + (y | 0) * this.width, color3, false); + } toJSON() { return { width: this.width, height: this.height, buffer: Array.from(this.u8) }; } - get(x2, y) { - return this.view.getUint32((x2 | 0) - 1 + ((y | 0) - 1) * this.width, false); - } scale(type, factor) { return this.resize(type, factor * this.width, factor * this.height); } overlay(frame, x2 = 0, y = 0) { - return overlay_exports.overlay(this, frame, x2 | 0, y | 0), this; + return overlay_exports.blend(this, frame, x2 | 0, y | 0), this; } replace(frame, x2 = 0, y = 0) { return overlay_exports.replace(this, frame, x2 | 0, y | 0), this; } - set(x2, y, color3) { - this.view.setUint32((x2 | 0) - 1 + ((y | 0) - 1) * this.width, color3, false); - } at(x2, y) { - const offset = 4 * ((x2 | 0) - 1 + ((y | 0) - 1) * this.width); + const offset = 4 * ((x2 | 0) + (y | 0) * this.width); return this.u8.subarray(offset, 4 + offset); } static from(framebuffer2) { @@ -2250,49 +2237,49 @@ var framebuffer = class { } static decode(format, buffer) { if (format !== "png") - throw new TypeError("invalid image format"); + throw new RangeError("invalid image format"); else return framebuffer.from(decode(buffer)); } encode(format, options = {}) { var _a2; if (format !== "png") - throw new Error("invalid image format"); + throw new RangeError("invalid image format"); else return encode(this.u8, { channels: 4, width: this.width, height: this.height, level: (_a2 = { none: 0, fast: 3, default: 6, best: 9 }[options.compression]) != null ? _a2 : 3 }); } + pixels(type) { + if (type === "rgba") + return iterator_exports.rgba(this); + if (!type || type === "int") + return iterator_exports.u32(this); + throw new RangeError("invalid iterator type"); + } flip(type) { if (type === "vertical") flip_exports.vertical(this); else if (type === "horizontal") flip_exports.horizontal(this); else - throw new TypeError("invalid flip type"); + throw new RangeError("invalid flip type"); return this; } - cut(type, arg0, arg1, arg2, arg3) { - if (type === "circle") - return crop_exports.circle(arg0 || 0, this); - else if (type === "box") - return crop_exports.cut(arg0 | 0, arg1 | 0, arg2 | 0, arg3 | 0, this); - else - throw new TypeError("invalid cut type"); - } crop(type, arg0, arg1, arg2, arg3) { if (type === "circle") crop_exports.circle(arg0 || 0, this); else if (type === "box") crop_exports.crop(arg0 | 0, arg1 | 0, arg2 | 0, arg3 | 0, this); else - throw new TypeError("invalid crop type"); + throw new RangeError("invalid crop type"); return this; } - pixels(type) { - if (type === "rgba") - return iterator_exports.rgba(this); - if (!type || type === "int") - return iterator_exports.u32(this); - throw new TypeError("invalid iterator type"); + cut(type, arg0, arg1, arg2, arg3) { + if (type === "circle") + return crop_exports.circle(arg0 || 0, this.clone()); + else if (type === "box") + return crop_exports.cut(arg0 | 0, arg1 | 0, arg2 | 0, arg3 | 0, this); + else + throw new RangeError("invalid cut type"); } rotate(deg, resize = true) { if ((deg %= 360) === 0) @@ -2315,7 +2302,7 @@ var framebuffer = class { else if (type === "gaussian") blur_exports.gaussian(+arg0, this); else - throw new TypeError("invalid blur type"); + throw new RangeError("invalid blur type"); return this; } fill(color3) { @@ -2324,7 +2311,7 @@ var framebuffer = class { fill_exports.fn(color3, this); else if (type === "number") fill_exports.color(color3, this); - else if (color3 instanceof color_default) + else if (color3 instanceof color) fill_exports.color(color3.valueOf(), this); else if (Array.isArray(color3)) fill_exports.color(color_exports.from_rgba(...color3), this); @@ -2337,12 +2324,12 @@ var framebuffer = class { const nt = typeof color3; if (ot === nt && ot === "number") fill_exports.swap(old, color3, this); - else if (old instanceof color_default && color3 instanceof color_default) + else if (old instanceof color && color3 instanceof color) fill_exports.swap(old.valueOf(), color3.valueOf(), this); else if (Array.isArray(old) && Array.isArray(color3)) fill_exports.swap(color_exports.from_rgba(...old), color_exports.from_rgba(...color3), this); else - throw new TypeError("invalid swap color"); + throw new RangeError("invalid swap color"); return this; } resize(type, width, height) { @@ -2355,11 +2342,10 @@ var framebuffer = class { else if (type === "nearest") resize_exports.nearest(width, height, this); else - throw new TypeError("invalid resize type"); + throw new RangeError("invalid resize type"); return this; } }; -var framebuffer_default = framebuffer; // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { Color diff --git a/v2/framebuffer.mjs b/v2/framebuffer.mjs index 4bf2f71..e59efd4 100644 --- a/v2/framebuffer.mjs +++ b/v2/framebuffer.mjs @@ -1,9 +1,13 @@ -import Color from './ops/color.js'; -import { view } from './util/mem.js'; -import * as ops from './ops/index.js'; -import * as png from '../png/src/png.js'; +import Color from './ops/color.mjs'; +import { view } from './util/mem.mjs'; +import * as ops from './ops/index.mjs'; +import * as png from '../png/src/png.mjs'; export { Color }; + +// todo: tree shakable context +// todo: make errors more verbose + export default class framebuffer { constructor(width, height, buffer) { this.width = width | 0; @@ -11,57 +15,57 @@ export default class framebuffer { this.u8 = buffer ? view(buffer) : new Uint8Array(4 * this.width * this.height); this.view = new DataView(this.u8.buffer, this.u8.byteOffset, this.u8.byteLength); this.u32 = new Uint32Array(this.u8.buffer, this.u8.byteOffset, this.u8.byteLength / 4); - if (this.u8.length !== 4 * this.width * this.height) throw new TypeError('invalid capacity of buffer'); + if (this.u8.length !== 4 * this.width * this.height) throw new RangeError('invalid capacity of buffer'); } [Symbol.iterator]() { return ops.iterator.cords(this); } toString() { return `framebuffer<${this.width}x${this.height}>`; } + get(x, y) { return this.view.getUint32((x | 0) + (y | 0) * this.width, false); } clone() { return new this.constructor(this.width, this.height, this.u8.slice()); } + set(x, y, color) { this.view.setUint32((x | 0) + (y | 0) * this.width, color, false); } toJSON() { return { width: this.width, height: this.height, buffer: Array.from(this.u8) } } - get(x, y) { return this.view.getUint32(((x | 0) - 1) + ((y | 0) - 1) * this.width, false); } scale(type, factor) { return this.resize(type, factor * this.width, factor * this.height); } - overlay(frame, x = 0, y = 0) { return (ops.overlay.overlay(this, frame, x | 0, y | 0), this); } + overlay(frame, x = 0, y = 0) { return (ops.overlay.blend(this, frame, x | 0, y | 0), this); } replace(frame, x = 0, y = 0) { return (ops.overlay.replace(this, frame, x | 0, y | 0), this); } - set(x, y, color) { this.view.setUint32(((x | 0) - 1) + ((y | 0) - 1) * this.width, color, false); } - at(x, y) { const offset = 4 * (((x | 0) - 1) + ((y | 0) - 1) * this.width); return this.u8.subarray(offset, 4 + offset); } + at(x, y) { const offset = 4 * ((x | 0) + (y | 0) * this.width); return this.u8.subarray(offset, 4 + offset); } static from(framebuffer) { return new this(framebuffer.width, framebuffer.height, framebuffer.u8 || framebuffer.buffer); } - static decode(format, buffer) { if (format !== 'png') throw new TypeError('invalid image format'); else return framebuffer.from(png.decode(buffer)); } + static decode(format, buffer) { if (format !== 'png') throw new RangeError('invalid image format'); else return framebuffer.from(png.decode(buffer)); } encode(format, options = {}) { - if (format !== 'png') throw new Error('invalid image format'); + if (format !== 'png') throw new RangeError('invalid image format'); else return png.encode(this.u8, { channels: 4, width: this.width, height: this.height, level: ({ none: 0, fast: 3, default: 6, best: 9 })[options.compression] ?? 3 }); } + pixels(type) { + if ('rgba' === type) return ops.iterator.rgba(this); + if (!type || 'int' === type) return ops.iterator.u32(this); + + throw new RangeError('invalid iterator type'); + } + flip(type) { if (type === 'vertical') ops.flip.vertical(this); else if (type === 'horizontal') ops.flip.horizontal(this); - else throw new TypeError('invalid flip type'); + else throw new RangeError('invalid flip type'); return this; } - cut(type, arg0, arg1, arg2, arg3) { - if (type === 'circle') return ops.crop.circle(arg0 || 0, this); - else if (type === 'box') return ops.crop.cut(arg0 | 0, arg1 | 0, arg2 | 0, arg3 | 0, this); - - else throw new TypeError('invalid cut type'); - } - crop(type, arg0, arg1, arg2, arg3) { if (type === 'circle') ops.crop.circle(arg0 || 0, this); else if (type === 'box') ops.crop.crop(arg0 | 0, arg1 | 0, arg2 | 0, arg3 | 0, this); - else throw new TypeError('invalid crop type'); + else throw new RangeError('invalid crop type'); return this; } - pixels(type) { - if ('rgba' === type) return ops.iterator.rgba(this); - if (!type || 'int' === type) return ops.iterator.u32(this); + cut(type, arg0, arg1, arg2, arg3) { + if (type === 'circle') return ops.crop.circle(arg0 || 0, this.clone()); + else if (type === 'box') return ops.crop.cut(arg0 | 0, arg1 | 0, arg2 | 0, arg3 | 0, this); - throw new TypeError('invalid iterator type'); + else throw new RangeError('invalid cut type'); } rotate(deg, resize = true) { @@ -80,7 +84,7 @@ export default class framebuffer { else if (type === 'box') ops.blur.box(+arg0, this); else if (type === 'gaussian') ops.blur.gaussian(+arg0, this); - else throw new TypeError('invalid blur type'); + else throw new RangeError('invalid blur type'); return this; } @@ -104,7 +108,7 @@ export default class framebuffer { else if (old instanceof Color && color instanceof Color) ops.fill.swap(old.valueOf(), color.valueOf(), this); else if (Array.isArray(old) && Array.isArray(color)) ops.fill.swap(ops.color.from_rgba(...old), ops.color.from_rgba(...color), this); - else throw new TypeError('invalid swap color'); + else throw new RangeError('invalid swap color'); return this; } @@ -115,7 +119,7 @@ export default class framebuffer { else if (type === 'linear') ops.resize.linear(width, height, this); else if (type === 'nearest') ops.resize.nearest(width, height, this); - else throw new TypeError('invalid resize type'); + else throw new RangeError('invalid resize type'); return this; } diff --git a/v2/framebuffer.rs b/v2/framebuffer.rs new file mode 100644 index 0000000..64d8ad1 --- /dev/null +++ b/v2/framebuffer.rs @@ -0,0 +1,1264 @@ +#![allow(dead_code)] +#![warn(clippy::perf)] +#![feature(decl_macro)] +#![feature(const_mut_refs)] +#![feature(unchecked_math)] +#![warn(clippy::complexity)] +#![feature(core_intrinsics)] +#![warn(clippy::correctness)] +#![allow(non_camel_case_types)] +#![feature(downcast_unchecked)] +#![allow(non_upper_case_globals)] +#![feature(const_slice_from_raw_parts)] +#![feature(const_fn_floating_point_arithmetic)] + +macro size_of { ($type:ty) => { std::mem::size_of::<$type>() } } +#[inline] const fn alloc_len(size: usize) -> usize { return alloc_align(size).size(); } +#[inline(always)] const unsafe fn unreachable() -> ! { std::hint::unreachable_unchecked(); } +#[inline] fn alloc(size: usize) -> *mut u8 { unsafe { return std::alloc::alloc(alloc_align(size)); } } +#[inline] fn free(ptr: *mut u8, size: usize) { unsafe { std::alloc::dealloc(ptr, alloc_align(size)); } } +#[inline] fn calloc(size: usize) -> *mut u8 { unsafe { return std::alloc::alloc_zeroed(alloc_align(size)); } } +#[inline] const fn alloc_align(size: usize) -> std::alloc::Layout { return unsafe { std::alloc::Layout::from_size_align_unchecked(size, 16) }; } + +type fb = framebuffer; + +pub struct framebuffer { + pub width: usize, + pub height: usize, + ptr: (bool, *mut u8), +} + +unsafe impl Send for framebuffer {} +unsafe impl Sync for framebuffer {} + +pub trait framebuffer_from { + fn from(width: usize, height: usize, container: T) -> fb; +} + +impl Drop for framebuffer { + fn drop(&mut self) { if self.ptr.0 { free(self.as_mut_ptr(), self.len()); } } +} + +impl std::ops::Deref for framebuffer { + type Target = [u8]; fn deref(&self) -> &Self::Target { return unsafe { std::slice::from_raw_parts(self.as_ptr(), self.len()) }; } +} + +impl std::ops::DerefMut for framebuffer { + fn deref_mut(&mut self) -> &mut Self::Target { return unsafe { std::slice::from_raw_parts_mut(self.as_mut_ptr(), self.len()) }; } +} + +impl std::ops::IndexMut<(usize, usize)> for framebuffer { + fn index_mut(&mut self, index: (usize, usize)) -> &mut Self::Output { return unsafe { &mut *(self.as_mut_ptr::().add(index.0 + index.1 * self.width) as *mut colors::rgba) }; } +} + +impl std::ops::Index<(usize, usize)> for framebuffer { + type Output = colors::rgba; fn index(&self, index: (usize, usize)) -> &Self::Output { return unsafe { &*(self.as_ptr::().add(index.0 + index.1 * self.width) as *mut colors::rgba) }; } +} + +impl Clone for framebuffer { + fn clone(&self) -> Self { + let ptr = alloc(self.len()); + unsafe { self.ptr.1.copy_to_nonoverlapping(ptr, self.len()); } + return Self { width: self.width, height: self.height, ptr: (true, ptr) }; + } +} + + +impl framebuffer_from<*mut T> for *mut T { fn from(width: usize, height: usize, container: *mut T) -> fb { return fb { width, height, ptr: (false, container as *mut u8) }; } } +impl framebuffer_from<&[T]> for &[T] { fn from(width: usize, height: usize, container: &[T]) -> fb { return fb { width, height, ptr: (false, container.as_ptr() as *mut u8) }; } } +impl framebuffer_from<*const T> for *const T { fn from(width: usize, height: usize, container: *const T) -> fb { return fb { width, height, ptr: (false, container as *mut u8) }; } } +impl framebuffer_from<&Vec> for &Vec { fn from(width: usize, height: usize, container: &Vec) -> fb { return fb { width, height, ptr: (false, container.as_ptr() as *mut u8) }; } } +impl framebuffer_from<&mut [T]> for &mut [T] { fn from(width: usize, height: usize, container: &mut [T]) -> fb { return fb { width, height, ptr: (false, container.as_mut_ptr() as *mut u8) }; } } +impl framebuffer_from<&mut Vec> for &mut Vec { fn from(width: usize, height: usize, container: &mut Vec) -> fb { return fb { width, height, ptr: (false, container.as_mut_ptr() as *mut u8) }; } } +impl framebuffer_from for colors::rgba { fn from(width: usize, height: usize, container: colors::rgba) -> fb { let mut fb = unsafe { framebuffer::new_uninit(width, height) }; ops::fill::color(&mut fb, container); return fb; } } +impl framebuffer_from for colors::rgb { fn from(width: usize, height: usize, container: colors::rgb) -> fb { let mut fb = unsafe { framebuffer::new_uninit(width, height) }; ops::fill::color(&mut fb, container.into()); return fb; } } +impl framebuffer_from for F where F: Fn(usize, usize) -> T { fn from(width: usize, height: usize, container: F) -> fb { let mut fb = unsafe { framebuffer::new_uninit(width, height) }; ops::fill::function(&mut fb, container); return fb; } } + + +impl framebuffer { + pub fn new(width: usize, height: usize) -> Self { return Self { width, height, ptr: (true, calloc(4 * width * height)) }; } + pub fn from>(width: usize, height: usize, container: T) -> Self { return T::from(width, height, container); } + pub unsafe fn new_uninit(width: usize, height: usize) -> Self { return Self { width, height, ptr: (true, alloc(4 * width * height)) }; } + + pub const fn len(&self) -> usize { return 4 * self.width * self.height; } + pub const fn as_ptr(&self) -> *const T { return self.ptr.1 as *const T; } + pub const fn as_mut_ptr(&mut self) -> *mut T { return self.ptr.1 as *mut T; } + pub const fn as_slice(&self) -> &[T] { return unsafe { std::slice::from_raw_parts(self.as_ptr(), self.len() / size_of!(T)) }; } + pub const fn as_mut_slice(&mut self) -> &mut [T] { return unsafe { std::slice::from_raw_parts_mut(self.as_mut_ptr(), self.len() / size_of!(T)) }; } + pub fn into_vec(mut self) -> Vec { self.ptr.0 = false; return unsafe { Vec::from_raw_parts(self.as_mut_ptr(), self.len() / size_of!(T), alloc_len(self.len()) / size_of!(T)) }; } +} + +pub mod colors { + #[repr(C)] #[derive(Copy, Clone, Debug)] pub struct rgb { pub r: u8, pub g: u8, pub b: u8 } + #[repr(C)] #[derive(Copy, Clone, Debug)] pub struct rgba { pub r: u8, pub g: u8, pub b: u8, pub a: u8 } + + impl From for rgb { #[inline] fn from(c: rgba) -> rgb { return rgb { r: c.r, g: c.g, b: c.b }; } } + impl From for rgba { #[inline] fn from(c: rgb) -> rgba { return rgba { r: c.r, g: c.g, b: c.b, a: 255 }; } } + impl From for u32 { #[inline] fn from(c: rgb) -> u32 { return c.r as u32 | ((c.g as u32) << 8) | ((c.b as u32) << 16) | (255 << 24); } } + impl From for u32 { #[inline] fn from(c: rgba) -> u32 { return c.r as u32 | ((c.g as u32) << 8) | ((c.b as u32) << 16) | ((c.a as u32) << 24); } } + impl From for rgb { #[inline] fn from(c: u32) -> rgb { return rgb { r: (c & 0xFF) as u8, g: ((c >> 8) & 0xFF) as u8, b: ((c >> 16) & 0xFF) as u8 }; } } + impl From for rgba { #[inline] fn from(c: u32) -> rgba { return rgba { r: (c & 0xFF) as u8, g: ((c >> 8) & 0xFF) as u8, b: ((c >> 16) & 0xFF) as u8, a: (c >> 24) as u8 }; } } + + pub fn blend(bg: u32, fg: u32) -> u32 { + let fa = fg >> 24; + let alpha = 1 + fa; + let inv_alpha = 256 - fa; + let r = (alpha * (fg & 0xff) + inv_alpha * (bg & 0xff)) >> 8; + let g = (alpha * ((fg >> 8) & 0xff) + inv_alpha * ((bg >> 8) & 0xff)) >> 8; + let b = (alpha * ((fg >> 16) & 0xff) + inv_alpha * ((bg >> 16) & 0xff)) >> 8; + return r | ((g & 0xff) << 8) | ((b & 0xff) << 16) | (fa.max(bg >> 24) << 24); + } +} + +pub mod ops { + use super::*; + + pub mod filter { + use super::*; + + pub fn opacity(fb: &mut fb, mut amount: f32) { + amount = amount.clamp(0.0, 1.0); + let u8 = unsafe { fb.as_mut_ptr::().offset(3) }; + + let mut offset = 0; + let len = fb.len(); + while len > offset { + use std::intrinsics::{fmul_fast as fm, float_to_int_unchecked as fi}; + unsafe { *u8.add(offset) = fi::(fm(amount, *u8.add(offset) as f32)); } + + offset += 4; + } + } + + pub fn brightness(fb: &mut fb, amount: f32) { + let u32 = fb.as_mut_ptr::(); + + for o in 0..(fb.len() / 4) { + unsafe { + use std::intrinsics::{fmul_fast as fm, float_to_int_unchecked as fi}; + + let c = *u32.add(o); + let r = fi::(fm(amount, (c & 0xff) as f32)).min(255); + let g = fi::(fm(amount, ((c >> 8) & 0xff) as f32)).min(255); + let b = fi::(fm(amount, ((c >> 16) & 0xff) as f32)).min(255); + + *u32.add(o) = r | (g << 8) | (b << 16) | (c >> 24 << 24); + } + } + } + + pub fn contrast(fb: &mut fb, amount: f32) { + let u32 = fb.as_mut_ptr::(); + let i = 255.0 * (0.5 - (0.5 * amount)); + + for o in 0..(fb.len() / 4) { + unsafe { + use std::intrinsics::{fadd_fast as fa, fmul_fast as fm, float_to_int_unchecked as fi}; + + let c = *u32.add(o); + let r = fi::(fa(i, fm(amount, (c & 0xff) as f32))).min(255); + let g = fi::(fa(i, fm(amount, ((c >> 8) & 0xff) as f32))).min(255); + let b = fi::(fa(i, fm(amount, ((c >> 16) & 0xff) as f32))).min(255); + + *u32.add(o) = r | (g << 8) | (b << 16) | (c >> 24 << 24); + } + } + } + + pub fn saturate(fb: &mut fb, amount: f32) { + let u32 = fb.as_mut_ptr::(); + + let filter: [f32; 9] = [ + 0.213 + 0.787 * amount, 0.715 - 0.715 * amount, 0.072 - 0.072 * amount, + 0.213 - 0.213 * amount, 0.715 + 0.285 * amount, 0.072 - 0.072 * amount, + 0.213 - 0.213 * amount, 0.715 - 0.715 * amount, 0.072 + 0.928 * amount, + ]; + + for o in 0..(fb.len() / 4) { + unsafe { + use std::intrinsics::{fadd_fast as fa, fmul_fast as fm, float_to_int_unchecked as fi}; + + let c = *u32.add(o); + let rr = (c & 0xff) as f32; + let gg = ((c >> 8) & 0xff) as f32; + let bb = ((c >> 16) & 0xff) as f32; + let r = fi::(fa(fm(rr, filter[0]), fa(fm(gg, filter[1]), fm(bb, filter[2])))).clamp(0, 255); + let g = fi::(fa(fm(rr, filter[3]), fa(fm(gg, filter[4]), fm(bb, filter[5])))).clamp(0, 255); + let b = fi::(fa(fm(rr, filter[6]), fa(fm(gg, filter[7]), fm(bb, filter[8])))).clamp(0, 255); + + *u32.add(o) = r | (g << 8) | (b << 16) | (c >> 24 << 24); + } + } + } + + pub fn sepia(fb: &mut fb, mut amount: f32) { + let u32 = fb.as_mut_ptr::(); + amount = (1.0 - amount).clamp(0.0, 1.0); + + let filter: [f32; 9] = [ + 0.393 + 0.607 * amount, 0.769 - 0.769 * amount, 0.189 - 0.189 * amount, + 0.349 - 0.349 * amount, 0.686 + 0.314 * amount, 0.168 - 0.168 * amount, + 0.272 - 0.272 * amount, 0.534 - 0.534 * amount, 0.131 + 0.869 * amount, + ]; + + for o in 0..(fb.len() / 4) { + unsafe { + use std::intrinsics::{fadd_fast as fa, fmul_fast as fm, float_to_int_unchecked as fi}; + + let c = *u32.add(o); + let rr = (c & 0xff) as f32; + let gg = ((c >> 8) & 0xff) as f32; + let bb = ((c >> 16) & 0xff) as f32; + let r = fi::(fa(fm(rr, filter[0]), fa(fm(gg, filter[1]), fm(bb, filter[2])))).clamp(0, 255); + let g = fi::(fa(fm(rr, filter[3]), fa(fm(gg, filter[4]), fm(bb, filter[5])))).clamp(0, 255); + let b = fi::(fa(fm(rr, filter[6]), fa(fm(gg, filter[7]), fm(bb, filter[8])))).clamp(0, 255); + + *u32.add(o) = r | (g << 8) | (b << 16) | (c >> 24 << 24); + } + } + } + + pub fn grayscale(fb: &mut fb, mut amount: f32) { + let u32 = fb.as_mut_ptr::(); + amount = (1.0 - amount).clamp(0.0, 1.0); + + let filter: [f32; 9] = [ + 0.2126 + 0.7874 * amount, 0.7152 - 0.7152 * amount, 0.0722 - 0.0722 * amount, + 0.2126 - 0.2126 * amount, 0.7152 + 0.2848 * amount, 0.0722 - 0.0722 * amount, + 0.2126 - 0.2126 * amount, 0.7152 - 0.7152 * amount, 0.0722 + 0.9278 * amount, + ]; + + for o in 0..(fb.len() / 4) { + unsafe { + use std::intrinsics::{fadd_fast as fa, fmul_fast as fm, float_to_int_unchecked as fi}; + + let c = *u32.add(o); + let rr = (c & 0xff) as f32; + let gg = ((c >> 8) & 0xff) as f32; + let bb = ((c >> 16) & 0xff) as f32; + let r = fi::(fa(fm(rr, filter[0]), fa(fm(gg, filter[1]), fm(bb, filter[2])))).clamp(0, 255); + let g = fi::(fa(fm(rr, filter[3]), fa(fm(gg, filter[4]), fm(bb, filter[5])))).clamp(0, 255); + let b = fi::(fa(fm(rr, filter[6]), fa(fm(gg, filter[7]), fm(bb, filter[8])))).clamp(0, 255); + + *u32.add(o) = r | (g << 8) | (b << 16) | (c >> 24 << 24); + } + } + } + + pub fn hue_rotate(fb: &mut fb, deg: f32) { + let u32 = fb.as_mut_ptr::(); + let cos = f32::cos(deg.to_radians()); + let sin = f32::sin(deg.to_radians()); + + let filter: [f32; 9] = [ + 0.213 + cos * 0.787 - sin * 0.213, 0.715 - cos * 0.715 - sin * 0.715, 0.072 - cos * 0.072 + sin * 0.928, + 0.213 - cos * 0.213 + sin * 0.143, 0.715 + cos * 0.285 + sin * 0.140, 0.072 - cos * 0.072 - sin * 0.283, + 0.213 - cos * 0.213 - sin * 0.787, 0.715 - cos * 0.715 + sin * 0.715, 0.072 + cos * 0.928 + sin * 0.072, + ]; + + for o in 0..(fb.len() / 4) { + unsafe { + use std::intrinsics::{fadd_fast as fa, fmul_fast as fm}; + #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] const fn fi<_f, _i>(x: f32) -> u32 { return x as u32; } + #[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))] use std::intrinsics::{float_to_int_unchecked as fi}; + + let c = *u32.add(o); + let rr = (c & 0xff) as f32; + let gg = ((c >> 8) & 0xff) as f32; + let bb = ((c >> 16) & 0xff) as f32; + let r = fi::(fa(fm(rr, filter[0]), fa(fm(gg, filter[1]), fm(bb, filter[2])))).clamp(0, 255); + let g = fi::(fa(fm(rr, filter[3]), fa(fm(gg, filter[4]), fm(bb, filter[5])))).clamp(0, 255); + let b = fi::(fa(fm(rr, filter[6]), fa(fm(gg, filter[7]), fm(bb, filter[8])))).clamp(0, 255); + + *u32.add(o) = r | (g << 8) | (b << 16) | (c >> 24 << 24); + } + } + } + + pub fn drop_shadow(fb: &mut fb, x: isize, y: isize, sigma: f32, color: Option) { + let mut old = fb.clone(); + let u32 = old.as_mut_ptr::(); + ops::blur::gaussian(&mut old, sigma); + + if color.is_some() { + unsafe { + let cc: u32 = color.unwrap_unchecked().into(); + + let ca = cc >> 24; + let cc = cc & 0xffffff; + + for o in 0..(fb.len() / 4) { + let c = *u32.add(o); + if 0 != (c >> 24) { *u32.add(o) = cc | (c >> 24 << 24) } + } + + if ca != 255 { ops::filter::opacity(&mut old, 1.0 / 255.0 * ca as f32); } + } + } + + ops::overlay::background(fb, &old, x, y); + } + + pub fn invert(fb: &mut fb, mut amount: f32) { + let u32 = fb.as_mut_ptr::(); + amount = amount.clamp(0.0, 1.0); + + if 1.0 == amount { + for o in 0..(fb.len() / 4) { + unsafe { + let c = *u32.add(o); + *u32.add(o) = !c & 0xffffff | (c >> 24 << 24); + } + } + } + + else { + let inv = 1.0 - amount; + + for o in 0..(fb.len() / 4) { + use std::intrinsics::{fadd_fast as fa, fsub_fast as fs, fmul_fast as fm, float_to_int_unchecked as fi}; + + unsafe { + let c = *u32.add(o); + let r = (c & 0xff) as f32; + let g = ((c >> 8) & 0xff) as f32; + let b = ((c >> 16) & 0xff) as f32; + let r = fi::(fa(fm(r, amount), fm(inv, fs(255.0, r)))); + let g = fi::(fa(fm(g, amount), fm(inv, fs(255.0, g)))); + let b = fi::(fa(fm(b, amount), fm(inv, fs(255.0, b)))); + *u32.add(o) = r | ((g & 0xff) << 8) | ((b & 0xff) << 16) | (c >> 24 << 24); + } + } + } + } + } + + pub mod crop { + use super::*; + use std::ops::Neg; + + pub fn r#box(fb: &fb, x: isize, y: isize, width: usize, height: usize) -> fb { + let old = fb; + let mut fb = fb::new(width, height); + ops::overlay::replace(&mut fb, old, x.neg(), y.neg()); + + return fb; + } + } + + pub mod flip { + use super::*; + + pub fn horizontal(fb: &mut fb) { + let width = fb.width; + let height = fb.height; + let u32 = fb.as_mut_ptr::(); + for y in 0..height { unsafe { std::slice::from_raw_parts_mut(u32.add(y * width), width).reverse(); } } + } + + pub fn vertical(fb: &mut fb) { + let width = fb.width; + let height = fb.height; + let u32 = fb.as_mut_ptr::(); + + for y in 0..(height / 2) { + let yoffset = y * width; + let yboffset = width * (height - 1 - y); + for x in 0..width { unsafe { std::ptr::swap(u32.add(x + yoffset), u32.add(x + yboffset)) }; } + } + } + } + + pub mod fill { + use super::*; + + pub trait fill_value { fn value(self) -> u32; } + impl fill_value for u32 { fn value(self) -> u32 { return self; } } + impl fill_value for colors::rgb { fn value(self) -> u32 { return self.into(); } } + impl fill_value for colors::rgba { fn value(self) -> u32 { return self.into(); } } + + pub fn function(fb: &mut fb, f: F) where F: Fn(usize, usize) -> T { + let width = fb.width; + let height = fb.height; + let u32 = fb.as_mut_ptr::(); + + for y in 0..height { + let yoffset = y * width; + for x in 0..width { unsafe { *u32.add(x + yoffset) = f(x, y).value(); } } + } + } + + pub fn color(fb: &mut fb, color: colors::rgba) { + if color.r == color.g && color.r == color.b && color.r == color.a { unsafe { fb.as_mut_ptr::().write_bytes(color.r, fb.len()); } } + + else { + let width = fb.width; + let height = fb.height; + let u32 = fb.as_mut_ptr::(); + unsafe { std::slice::from_raw_parts_mut(u32, width).fill(color.into()); } + for y in 1..height { unsafe { u32.copy_to_nonoverlapping(u32.add(y * width), width); } } + } + } + + pub fn background(fb: &mut fb, color: colors::rgba) { + let width = fb.width; + let bg = color.into(); + let height = fb.height; + let u32 = fb.as_mut_ptr::(); + + for y in 0..height { + let yoffset = y * width; + + for x in 0..width { + unsafe { + let fg = *u32.add(x + yoffset); + + match (fg >> 24) & 0xff { + 0xff => {}, + 0x00 => *u32.add(x + yoffset) = bg, + _ => *u32.add(x + yoffset) = colors::blend(bg, fg), + } + } + } + } + } + } + + pub mod rotate { + use super::*; + + pub fn rotate180(fb: &mut fb) { + fb.as_mut_slice::().reverse(); + } + + pub fn rotate90(fb: &mut fb) { + let width = fb.width; + let height = fb.height; + let u32 = fb.as_mut_ptr::(); + let o32 = alloc(fb.len()) as *mut u32; + unsafe { u32.copy_to_nonoverlapping(o32, fb.len() / 4); } + + + fb.width = height; + fb.height = width; + + for y in 0..height { + let yoffset = y * width; + let heighty1 = height - 1 - y; + for x in 0..width { unsafe { *u32.add(heighty1 + x * height) = *o32.add(x + yoffset); } } + } + + free(o32 as *mut u8, fb.len()); + } + + pub fn rotate270(fb: &mut fb) { + let width = fb.width; + let height = fb.height; + let u32 = fb.as_mut_ptr::(); + let o32 = alloc(fb.len()) as *mut u32; + unsafe { u32.copy_to_nonoverlapping(o32, fb.len() / 4); } + + fb.width = height; + fb.height = width; + + for y in 0..height { + let yoffset = y * width; + for x in 0..width { unsafe { *u32.add(y + height * (width - 1 - x)) = *o32.add(x + yoffset); } } + } + + free(o32 as *mut u8, fb.len()); + } + } + + pub mod overlay { + use super::*; + + pub fn replace(fb: &mut fb, fg: &fb, x: isize, y: isize) { + let f32 = fg.as_ptr::(); + let b32 = fb.as_mut_ptr::(); + let (bw, bh) = (fb.width as isize, fb.height as isize); + let (fw, fh) = (fg.width as isize, fg.height as isize); + + let top = y.max(0); + let left = x.max(0); + let ox = x.min(0).abs(); + let oy = y.min(0).abs(); + let width = bw.min(x + fw) - left; + let height = bh.min(y + fh) - top; + if 0 >= width || 0 >= height { return; } + + for yy in 0..height { + let yyoffset = ox + fw * (yy + oy); + let yoffset = left + bw * (yy + top); + unsafe { b32.offset(yoffset).copy_from(f32.offset(yyoffset), width as usize); } + } + } + + pub fn blend(fb: &mut fb, fg: &fb, x: isize, y: isize) { + let f32 = fg.as_ptr::(); + let b32 = fb.as_mut_ptr::(); + let (bw, bh) = (fb.width as isize, fb.height as isize); + let (fw, fh) = (fg.width as isize, fg.height as isize); + + let top = y.max(0); + let left = x.max(0); + let ox = x.min(0).abs(); + let oy = y.min(0).abs(); + let width = bw.min(x + fw) - left; + let height = bh.min(y + fh) - top; + if 0 >= width || 0 >= height { return; } + + for yy in 0..height { + let yyoffset = ox + fw * (yy + oy); + let yoffset = left + bw * (yy + top); + + for xx in 0..width { + unsafe { + let fg = *f32.offset(xx + yyoffset); + + match fg >> 24 { + 0x00 => {}, + 0xff => *b32.offset(xx + yoffset) = fg, + + fa => { + let alpha = 1 + fa; + let inv_alpha = 256 - fa; + let bg = *b32.offset(xx + yoffset); + let r = (alpha * (fg & 0xff) + inv_alpha * (bg & 0xff)) >> 8; + let g = (alpha * ((fg >> 8) & 0xff) + inv_alpha * ((bg >> 8) & 0xff)) >> 8; + let b = (alpha * ((fg >> 16) & 0xff) + inv_alpha * ((bg >> 16) & 0xff)) >> 8; + *b32.offset(xx + yoffset) = r | ((g & 0xff) << 8) | ((b & 0xff) << 16) | (fa.max(bg >> 24) << 24); + }, + } + } + } + } + } + + pub fn background(fb: &mut fb, bg: &fb, x: isize, y: isize) { + let bb32 = bg.as_ptr::(); + let b32 = fb.as_mut_ptr::(); + let (bw, bh) = (fb.width as isize, fb.height as isize); + let (fw, fh) = (bg.width as isize, bg.height as isize); + + let top = y.max(0); + let left = x.max(0); + let ox = x.min(0).abs(); + let oy = y.min(0).abs(); + let width = bw.min(x + fw) - left; + let height = bh.min(y + fh) - top; + if 0 >= width || 0 >= height { return; } + + for yy in 0..height { + let yyoffset = ox + fw * (yy + oy); + let yoffset = left + bw * (yy + top); + + for xx in 0..width { + unsafe { + let fg = *b32.offset(xx + yoffset); + + match fg >> 24 { + 0xff => {}, + 0x00 => *b32.offset(xx + yoffset) = *bb32.offset(xx + yyoffset), + + fa => { + let alpha = 1 + fa; + let inv_alpha = 256 - fa; + let bg = *bb32.offset(xx + yyoffset); + let r = (alpha * (fg & 0xff) + inv_alpha * (bg & 0xff)) >> 8; + let g = (alpha * ((fg >> 8) & 0xff) + inv_alpha * ((bg >> 8) & 0xff)) >> 8; + let b = (alpha * ((fg >> 16) & 0xff) + inv_alpha * ((bg >> 16) & 0xff)) >> 8; + *b32.offset(xx + yoffset) = r | ((g & 0xff) << 8) | ((b & 0xff) << 16) | (fa.max(bg >> 24) << 24); + }, + } + } + } + } + } + } + + pub mod resize { + use super::*; + + const fn lerp(a: u8, b: u8, t: f64) -> u8 { + return ((t * b as f64) + a as f64 * (1.0 - t)) as u8; + } + + fn clamped(x: usize, y: usize, width: usize, height: usize) -> usize { + return 4 * (x.clamp(0, width - 1) + width * y.clamp(0, height - 1)); + } + + const fn hermite(a: f64, b: f64, c: f64, d: f64, t: f64) -> f64 { + let cc = (c / 2.0) + (a / -2.0); + let bb = a + (c * 2.0) - (d / 2.0) - (b * 2.5); + let aa = (d / 2.0) + (a / -2.0) + (b * 1.5) - (c * 1.5); + + let t2 = t * t; + return b + (t * cc) + (bb * t2) + (t * aa * t2); + } + + pub fn nearest(fb: &fb, width: usize, height: usize) -> fb { + let owidth = fb.width; + let oheight = fb.height; + let o32 = fb.as_ptr::(); + let mut fb = unsafe { framebuffer::new_uninit(width, height) }; + + let u32 = fb.as_mut_ptr::(); + let xw = 1.0 / width as f64 * owidth as f64; + let yw = 1.0 / height as f64 * oheight as f64; + + for y in 0..height { + let yoffset = y * width; + let yyoffset = owidth * (yw * y as f64) as usize; + for x in 0..width { unsafe { *u32.add(x + yoffset) = *o32.add(yyoffset + (xw * x as f64) as usize); } }; + }; + + return fb; + } + + pub unsafe fn linear(fb: &fb, width: usize, height: usize) -> fb { + let owidth = fb.width; + let oheight = fb.height; + let o8 = fb.as_ptr::(); + let mut fb = framebuffer::new(width, height); + + let mut offset = 0; + let u8 = fb.as_mut_ptr::(); + let width1 = 1.0 / (width - 1) as f64; + let height1 = 1.0 / (height - 1) as f64; + + for y in 0..height { + let yy = oheight as f64 * (y as f64 * height1) - 0.5; + + let yyi = yy as usize; + let ty = yy - yyi as f64; + + for x in 0..width { + let xx = owidth as f64 * (x as f64 * width1) - 0.5; + + let xxi = xx as usize; + let tx = xx - xxi as f64; + + let s0 = clamped(xxi, yyi, owidth, oheight); + let s1 = clamped(1 + xxi, yyi, owidth, oheight); + let s2 = clamped(xxi, 1 + yyi, owidth, oheight); + let s3 = clamped(1 + xxi, 1 + yyi, owidth, oheight); + + // unsafe { + *u8.offset(offset) = lerp(lerp(*o8.add(s0), *o8.add(s2), tx), lerp(*o8.add(s1), *o8.add(s3), tx), ty); + *u8.offset(1 + offset) = lerp(lerp(*o8.add(1 + s0), *o8.add(1 + s2), tx), lerp(*o8.add(1 + s1), *o8.add(1 + s3), tx), ty); + *u8.offset(2 + offset) = lerp(lerp(*o8.add(2 + s0), *o8.add(2 + s2), tx), lerp(*o8.add(2 + s1), *o8.add(2 + s3), tx), ty); + *u8.offset(3 + offset) = lerp(lerp(*o8.add(3 + s0), *o8.add(3 + s2), tx), lerp(*o8.add(3 + s1), *o8.add(3 + s3), tx), ty); + // } + + offset += 4; + }; + }; + + return fb; + } + + pub unsafe fn cubic(fb: &fb, width: usize, height: usize) -> fb { + let owidth = fb.width; + let oheight = fb.height; + let o8 = fb.as_ptr::(); + let mut fb = framebuffer::new(width, height); + + let mut offset = 0; + let u8 = fb.as_mut_ptr::(); + let width1 = 1.0 / (width - 1) as f64; + let height1 = 1.0 / (height - 1) as f64; + + for y in 0..height { + let yy = oheight as f64 * (y as f64 * height1) - 0.5; + + let yyi = yy as usize; + let ty = yy - yyi as f64; + + for x in 0..width { + let xx = owidth as f64 * (x as f64 * width1) - 0.5; + + let xxi = xx as usize; + let tx = xx - xxi as f64; + + let s0 = clamped(xxi - 1, yyi - 1, owidth, oheight); + + let s1 = clamped(xxi, yyi - 1, owidth, oheight); + let s2 = clamped(1 + xxi, yyi - 1, owidth, oheight); + let s3 = clamped(2 + xxi, yyi - 1, owidth, oheight); + + let s4 = clamped(xxi - 1, yyi, owidth, oheight); + + let s5 = clamped(xxi, yyi, owidth, oheight); + let s6 = clamped(1 + xxi, yyi, owidth, oheight); + let s7 = clamped(2 + xxi, yyi, owidth, oheight); + + let s8 = clamped(xxi - 1, 1 + yyi, owidth, oheight); + + let s9 = clamped(xxi, 1 + yyi, owidth, oheight); + let s10 = clamped(1 + xxi, 1 + yyi, owidth, oheight); + let s11 = clamped(2 + xxi, 1 + yyi, owidth, oheight); + + let s12 = clamped(xxi - 1, 2 + yyi, owidth, oheight); + + let s13 = clamped(xxi, 2 + yyi, owidth, oheight); + let s14 = clamped(1 + xxi, 2 + yyi, owidth, oheight); + let s15 = clamped(2 + xxi, 2 + yyi, owidth, oheight); + + // unsafe { + let c0 = hermite(*o8.add(s0) as f64, *o8.add(s1) as f64, *o8.add(s2) as f64, *o8.add(s3) as f64, tx); + let c00 = hermite(*o8.add(1 + s0) as f64, *o8.add(1 + s1) as f64, *o8.add(1 + s2) as f64, *o8.add(1 + s3) as f64, tx); + let c000 = hermite(*o8.add(2 + s0) as f64, *o8.add(2 + s1) as f64, *o8.add(2 + s2) as f64, *o8.add(2 + s3) as f64, tx); + let c0000 = hermite(*o8.add(3 + s0) as f64, *o8.add(3 + s1) as f64, *o8.add(3 + s2) as f64, *o8.add(3 + s3) as f64, tx); + + let c1 = hermite(*o8.add(s4) as f64, *o8.add(s5) as f64, *o8.add(s6) as f64, *o8.add(s7) as f64, tx); + let c11 = hermite(*o8.add(1 + s4) as f64, *o8.add(1 + s5) as f64, *o8.add(1 + s6) as f64, *o8.add(1 + s7) as f64, tx); + let c111 = hermite(*o8.add(2 + s4) as f64, *o8.add(2 + s5) as f64, *o8.add(2 + s6) as f64, *o8.add(2 + s7) as f64, tx); + let c1111 = hermite(*o8.add(3 + s4) as f64, *o8.add(3 + s5) as f64, *o8.add(3 + s6) as f64, *o8.add(3 + s7) as f64, tx); + + let c2 = hermite(*o8.add(s8) as f64, *o8.add(s9) as f64, *o8.add(s10) as f64, *o8.add(s11) as f64, tx); + let c22 = hermite(*o8.add(1 + s8) as f64, *o8.add(1 + s9) as f64, *o8.add(1 + s10) as f64, *o8.add(1 + s11) as f64, tx); + let c222 = hermite(*o8.add(2 + s8) as f64, *o8.add(2 + s9) as f64, *o8.add(2 + s10) as f64, *o8.add(2 + s11) as f64, tx); + let c2222 = hermite(*o8.add(3 + s8) as f64, *o8.add(3 + s9) as f64, *o8.add(3 + s10) as f64, *o8.add(3 + s11) as f64, tx); + + let c3 = hermite(*o8.add(s12) as f64, *o8.add(s13) as f64, *o8.add(s14) as f64, *o8.add(s15) as f64, tx); + let c33 = hermite(*o8.add(1 + s12) as f64, *o8.add(1 + s13) as f64, *o8.add(1 + s14) as f64, *o8.add(1 + s15) as f64, tx); + let c333 = hermite(*o8.add(2 + s12) as f64, *o8.add(2 + s13) as f64, *o8.add(2 + s14) as f64, *o8.add(2 + s15) as f64, tx); + let c3333 = hermite(*o8.add(3 + s12) as f64, *o8.add(3 + s13) as f64, *o8.add(3 + s14) as f64, *o8.add(3 + s15) as f64, tx); + + *u8.offset(offset) = hermite(c0, c1, c2, c3, ty) as u8; + *u8.offset(1 + offset) = hermite(c00, c11, c22, c33, ty) as u8; + *u8.offset(2 + offset) = hermite(c000, c111, c222, c333, ty) as u8; + *u8.offset(3 + offset) = hermite(c0000, c1111, c2222, c3333, ty) as u8; + // } + + offset += 4; + }; + }; + + return fb; + } + } + + pub mod blur { + use super::*; + + pub fn gaussian(fb: &mut fb, sigma: f32) { + if 0.0 == sigma { return; } + + let cof = { + let a = (0.726f32).powi(2).exp() / sigma; + + let l = (-a).exp(); + let c = (-a * 2.0).exp(); + let k = (1.0 - l).powi(2) / (1.0 - c + a * l * 2.0); + + let a3 = c * -k; + let b1 = l * 2.0; + let a1 = l * k * (a - 1.0); + let a2 = l * k * (a + 1.0); + (k, a1, a2, a3, b1, -c, (k + a1) / (c - b1 + 1.0), (a2 + a3) / (c - b1 + 1.0)) + }; + + let width = fb.width; + let height = fb.height; + + unsafe { + let o8 = alloc(fb.len()); + let u8 = fb.as_mut_ptr::(); + let f32 = alloc(4 * 4 * width.max(height)) as *mut f32; + + u8.copy_to(o8, fb.len()); + gc(o8, u8, f32, width, height, cof); + gc(u8, o8, f32, height, width, cof); + + free(o8, fb.len()); + free(f32 as *mut u8, 4 * 4 * width.max(height)); + } + } + + unsafe fn gc(u8: *mut u8, o8: *mut u8, f32: *mut f32, width: usize, height: usize, (k, a1, a2, a3, b1, b2, lc, rc): (f32, f32, f32, f32, f32, f32, f32, f32)) { + use std::intrinsics::{fmul_fast as fm, fadd_fast as fa, float_to_int_unchecked as fi}; + + let width4 = 4 * width; + let height4 = 4 * height; + let hw1 = height * (width - 1); + + for y in 0..height { + let mut toffset = 0; + let mut ooffset = y * width4; + let mut offset = 4 * (y + hw1); + + let (mut por, mut pog, mut pob, mut poa) = (*o8.add(ooffset) as f32, *o8.add(1 + ooffset) as f32, *o8.add(2 + ooffset) as f32, *o8.add(3 + ooffset) as f32); + let (mut fur, mut fug, mut fub, mut fua) = (fm(lc, por), fm(lc, pog), fm(lc, pob), fm(lc, poa)); let (mut tur, mut tug, mut tub, mut tua) = (fur, fug, fub, fua); + + for _ in 0..width { + let (cor, cog, cob, coa) = (*o8.add(ooffset) as f32, *o8.add(1 + ooffset) as f32, *o8.add(2 + ooffset) as f32, *o8.add(3 + ooffset) as f32); + let (cur, cug, cub, cua) = (fm(k, cor) + fm(a1, por) + fm(b1, fur) + fm(b2, tur), fm(k, cog) + fm(a1, pog) + fm(b1, fug) + fm(b2, tug), fm(k, cob) + fm(a1, pob) + fm(b1, fub) + fm(b2, tub), fm(k, coa) + fm(a1, poa) + fm(b1, fua) + fm(b2, tua)); + + (tur, tug, tub, tua) = (fur, fug, fub, fua); + (fur, fug, fub, fua) = (cur, cug, cub, cua); + (por, pog, pob, poa) = (cor, cog, cob, coa); + + *f32.offset(toffset) = fur; + *f32.offset(1 + toffset) = fug; + *f32.offset(2 + toffset) = fub; + *f32.offset(3 + toffset) = fua; + + ooffset += 4; + toffset += 4; + } + + ooffset -= 4; + toffset -= 4; + + por = *o8.add(ooffset) as f32; + pog = *o8.add(1 + ooffset) as f32; + pob = *o8.add(2 + ooffset) as f32; + poa = *o8.add(3 + ooffset) as f32; + (tur, tug, tub, tua) = (fm(rc, por), fm(rc, pog), fm(rc, pob), fm(rc, poa)); + + (fur, fug, fub, fua) = (tur, tug, tub, tua); + let (mut cor, mut cog, mut cob, mut coa) = (por, pog, pob, poa); + + for _ in 0..width { + let (cur, cug, cub, cua) = (fm(a2, cor) + fm(a3, por) + fm(b1, fur) + fm(b2, tur), fm(a2, cog) + fm(a3, pog) + fm(b1, fug) + fm(b2, tug), fm(a2, cob) + fm(a3, pob) + fm(b1, fub) + fm(b2, tub), fm(a2, coa) + fm(a3, poa) + fm(b1, fua) + fm(b2, tua)); + + (tur, tug, tub, tua) = (fur, fug, fub, fua); + (fur, fug, fub, fua) = (cur, cug, cub, cua); + (por, pog, pob, poa) = (cor, cog, cob, coa); + + cor = *o8.add(ooffset) as f32; + cog = *o8.add(1 + ooffset) as f32; + cob = *o8.add(2 + ooffset) as f32; + coa = *o8.add(3 + ooffset) as f32; + *u8.add(offset) = fi(fa(fur, *f32.offset(toffset))); + *u8.add(1 + offset) = fi(fa(fug, *f32.offset(1 + toffset))); + *u8.add(2 + offset) = fi(fa(fub, *f32.offset(2 + toffset))); + *u8.add(3 + offset) = fi(fa(fua, *f32.offset(3 + toffset))); + + ooffset = ooffset.saturating_sub(4); + toffset = toffset.saturating_sub(4); + offset = offset.saturating_sub(height4); + } + } + } + } +} + +pub mod quant { + use super::*; + + struct bin { r: u32, g: u32, b: u32, a: u32, count: u32 } + + struct tbin { + n: u32, p: u32, + r: f32, g: f32, b: f32, a: f32, + la: u32, lb: u32, error: f32, count: f32, nearest: u32, + } + + pub struct result { + pub index: Vec, + pub palette: Vec, + pub transparency: Option, + } + + pub struct options { + pub fast: bool, + pub dither: bool, + pub colors: usize, + pub transparency: bool, + pub threshold: Option, + pub force_transparency: bool, + } + + impl Default for options { + fn default() -> Self { + return Self { + fast: false, + colors: 256, + dither: true, + threshold: None, + transparency: true, + force_transparency: false, + }; + } + } + + unsafe fn index(fb: &fb, _colors: usize, opt: &options, palette: &[colors::rgba], s: &(f32, f32, f32, f32)) -> Vec { + let mut index: Vec = Vec::with_capacity(fb.width * fb.height); + + let u8 = index.as_mut_ptr(); + let u32 = fb.as_ptr::(); + index.set_len(fb.width * fb.height); + let mut nearest: fnv::FnvHashMap = fnv::FnvHashMap::default(); + let mut closest: fnv::FnvHashMap = fnv::FnvHashMap::default(); + + if opt.fast { for o in 0..(fb.len() / 4) { *u8.add(o) = self::nearest(*u32.add(o), &palette, &s, &mut nearest); } } + else { for o in 0..(fb.len() / 4) { *u8.add(o) = self::closest(*u32.add(o), o, &palette, &s, &mut nearest, &mut closest); } } + + return index; + } + + unsafe fn link_neareast(o: usize, bins: *mut tbin, s: &(f32, f32, f32, f32)) { + let mut nearest = 0; + let mut e = f32::INFINITY; + let bin = &mut *bins.add(o); + + let n1 = bin.count; + let mut offset = bin.n; + let w = (bin.r, bin.g, bin.b, bin.a); + + while 0 != offset { + let b = &*bins.add(offset as usize); + + let mut err = + s.0 * (b.r - w.0).powi(2) + + s.1 * (b.g - w.1).powi(2) + + s.2 * (b.b - w.2).powi(2) + + s.3 * (b.a - w.3).powi(2); + + let n2 = b.count; + err *= (n1 * n2) / (n1 + n2); + if e > err { e = err; nearest = offset; } + offset = (*bins.offset(offset as isize)).n; + } + + bin.error = e; + bin.nearest = nearest; + } + + unsafe fn nearest(c: u32, palette: &[colors::rgba], s: &(f32, f32, f32, f32), cache: &mut fnv::FnvHashMap) -> u8 { + let old = cache.get(&c); + if old.is_some() { return *old.unwrap_unchecked(); } + + let a = (c >> 24) as f32; + let r = (c & 0xff) as f32; + let g = ((c >> 8) & 0xff) as f32; + let b = ((c >> 16) & 0xff) as f32; + + let mut offset = 0; + let p = palette.as_ptr(); + let mut m = f32::INFINITY; + + for o in 0..palette.len() { + let cc = *p.add(o); + let rr = cc.r as f32; + let gg = cc.g as f32; + let bb = cc.b as f32; + let aa = cc.a as f32; + let mut d = s.3 * (aa - a).powi(2); + + if d > m { continue; } + d += s.0 * (rr - r).powi(2); if d > m { continue; } + d += s.1 * (gg - g).powi(2); if d > m { continue; } + d += s.2 * (bb - b).powi(2); if d > m { continue; } + + m = d; offset = o as u8; + } + + cache.insert(c, offset); return offset; + } + + unsafe fn closest(c: u32, o: usize, palette: &[colors::rgba], s: &(f32, f32, f32, f32), nearest: &mut fnv::FnvHashMap, cache: &mut fnv::FnvHashMap) -> u8 { + let old = cache.get(&c); + + let m = if old.is_some() { *old.unwrap_unchecked() } else { + let a = (c >> 24) as f32; + let r = (c & 0xff) as f32; + let pp = palette.as_ptr(); + let g = ((c >> 8) & 0xff) as f32; + let b = ((c >> 16) & 0xff) as f32; + let mut m = (0u8, 0u8, f32::INFINITY, f32::INFINITY); + + for o in 0..palette.len() { + let cc = *pp.add(o); + let rr = cc.r as f32; + let gg = cc.g as f32; + let bb = cc.b as f32; + let aa = cc.a as f32; + let err = s.0 * (rr - r).powi(2) + s.1 * (gg - g).powi(2) + s.2 * (bb - b).powi(2) + s.3 * (aa - a).powi(2); + if m.2 > err { m.1 = m.0; m.3 = m.2; m.2 = err; m.0 = o as u8; } else if m.3 > err { m.3 = err; m.1 = o as u8; } + } + + if m.3 == f32::INFINITY { m.1 = m.0; } cache.insert(c, m); m + }; + + let l = palette.len(); + let mut oo = (1 + o) % 2; + if m.3 * 0.67 < (m.3 - m.2) { oo = 0 } else if m.0 > m.1 { oo = o % 2; } + + let err = match oo { 0 => m.2, 1 => m.3, _ => unreachable() }; + if err >= l as f32 { return self::nearest(c, palette, s, nearest); } + + return match oo { 0 => m.0, 1 => m.1, _ => unreachable() }; + } + + pub fn quantize(fb: &fb, options: &options) -> result { + let width = fb.width; + let height = fb.height; + let mut fb = fb.clone(); + let u32 = fb.as_mut_ptr::(); + let colors = options.colors.clamp(2, 256); + let mut s = (0.2126, 0.7152, 0.0722, 0.3333); + + if 32 >= colors { s = (1.0, 1.0, 1.0, 1.0); } + else if 512 > width || 512 > height { s = (0.299, 0.587, 0.114, s.3); } + + unsafe { + if !options.transparency { + s.3 = 0.0; + let threshold = options.threshold.unwrap_or(0x42) as u32; + + for o in 0..(fb.len() / 4) { + let a = *u32.add(o) >> 24; + *u32.add(0) = (if a < threshold { 0 } else { *u32.add(o) & 0xffffff }) | (255 << 24); + } + } else { + if options.threshold.is_none() { + for o in 0..(fb.len() / 4) { + let a = *u32.add(o) >> 24; + if a == 0 { *u32.add(0) = 0xffffff; } + } + } else { + let threshold = options.threshold.unwrap_unchecked() as u32; + + for o in 0..(fb.len() / 4) { + let a = *u32.add(o) >> 24; + *u32.add(0) = if a < threshold { 0xffffff } else { *u32.add(o) & 0xffffff | (255 << 24) }; + } + } + } + } + + let mut palette: Vec = vec![0.into(); colors]; + + if 2 < colors { + let (mut s, p) = unsafe { self::palette(&fb, colors, &options, &mut s) }; + + unsafe { + let ss = s; + let mut t = -1; + for o in 0..s { if 0 == (*p.add(o) >> 24) { t = o as isize; break; } } + if t == -1 && options.transparency && options.force_transparency { *p.add(if s == colors { s - 1 } else { s += 1; s - 1 }) = 0; } + + palette.as_mut_ptr().copy_from_nonoverlapping(p as _, s); palette.set_len(s); + + free(p as *mut u8, ss); + palette.sort_by(|&a, &b| u32::cmp(&b.into(), &a.into())); + } + } else { + unsafe { + *palette.get_unchecked_mut(0) = colors::rgba { r: 0, g: 0, b: 0, a: 255 }; + + let mut t = options.transparency && options.force_transparency; + if !t && options.transparency { for o in 0..(fb.len() / 4) { if 0 == (*u32.add(o) >> 24) { t = true; break; } } } + + *palette.get_unchecked_mut(1) = + if t { colors::rgba { r: 255, g: 255, b: 255, a: 0 } } + else { colors::rgba { r: 255, g: 255, b: 255, a: 255 } }; + } + } + + let mut t = None; + let index = unsafe { index(&fb, colors, &options, &palette, &s) }; + for o in 0..palette.len() { if 0 == palette[o].a { t = Some(o); break; } } + + return result { + index, + palette, + transparency: t, + }; + } + + unsafe fn palette(fb: &fb, colors: usize, options: &options, s: &mut (f32, f32, f32, f32)) -> (usize, *mut u32) { + let u32 = fb.as_ptr::(); + const BINS: usize = 2usize.pow(16); + + let (size, bins): (usize, *mut tbin) = { + let bins = calloc(BINS * size_of!(bin)) as *mut bin; + + let index = match options.fast { + true => |r: u32, g: u32, b: u32, a: u32| ((r & 0xF0) << 4) | (g & 0xF0) | (b >> 4) | ((a & 0xF0) << 8), + + false => match 64 <= colors && !options.transparency { + true => |r: u32, g: u32, b: u32, _: u32| ((r & 0xf8) << 8) | ((g & 0xfc) << 3) | (b >> 3), + false => |r: u32, g: u32, b: u32, a: u32| ((r & 0xf8) << 7) | ((g & 0xf8) << 2) | (b >> 3) | ((a & 0x80) << 8), + }, + }; + + for o in 0..(fb.len() / 4) { + let c = *u32.add(o); + + let a = c >> 24; + let r = c & 0xff; + let g = (c >> 8) & 0xff; + let b = (c >> 16) & 0xff; + + let mut bin = &mut *bins.add(index(r, g, b, a) as usize); + + bin.r += r; + bin.g += g; + bin.b += b; + bin.a += a; + bin.count += 1; + } + + let mut size = 0; + + for o in 0..BINS { + let bin = bins.add(o); + if 0 == (*bin).count { continue; } + bins.add(size).copy_from(bin, 1); size += 1; + } + + let tbin = calloc(size * size_of!(tbin)) as *mut tbin; + + for o in 0..size { + use std::intrinsics::{fdiv_fast as fd}; + + let bin = &*bins.add(o); + let tbin = &mut *tbin.add(o); + + let count = bin.count as f32; + + tbin.count = count; + tbin.r = fd(bin.r as f32, count); + tbin.g = fd(bin.g as f32, count); + tbin.b = fd(bin.b as f32, count); + tbin.a = fd(bin.a as f32, count); + } + + free(bins as *mut u8, BINS * size_of!(bin)); + + (size, tbin) + }; + + let q = { + let weight = colors as f32 / size as f32; + let mut e = if 16 <= colors { 1 } else { -1 }; + if 0.003 < weight && 0.005 > weight { e = 0; }; + + if s.1 < 1.0 && 0.025 > weight { + s.1 -= 3.0 * (0.025 + weight); + s.2 += 3.0 * (0.025 + weight); + } + + match e { + 0 => |count: f32| count, + -1 => |count: f32| count.cbrt() as u32 as f32, + + 1 => match 64 > colors { + true => |count: f32| count.sqrt(), + false => |count: f32| count.sqrt() as u32 as f32, + }, + + _ => unreachable(), + } + }; + + for o in 0..(size - 1) { + let bin = &mut *bins.add(o); + + bin.n = (o + 1) as u32; + bin.count = q(bin.count); + (*bins.add(o + 1)).p = o as u32; + } + + (*bins.add(size - 1)).count = q((*bins.add(size - 1)).count); + + let heap = calloc(4 * (1 + BINS)) as *mut u32; + + for o in 0..size { + link_neareast(o, bins, &s); + let err = (*bins.add(o)).error; + + *heap += 1; + let mut l = *heap; + + while 1 < l { + let h = *heap.add((l >> 1) as usize); + if err >= (*bins.add(h as usize)).error { break; } + + *heap.add(l as usize) = h; l >>= 1; + } + + *heap.add(l as usize) = o as u32; + } + + let ext = size as isize - colors as isize; + + for o in 0..ext { + let mut b; + + loop { + b = *heap.add(1); + let tb = &mut *bins.add(b as usize); + if (tb.la >= tb.lb) && (tb.la >= (*bins.add(tb.nearest as usize)).lb) { break; } + + if tb.lb == 0xffff { + *heap -= 1; + let h = 1 + *heap; + b = *heap.add(h as usize); + *heap.offset(1) = *heap.add(h as usize); + } else { link_neareast(b as usize, bins, &s); tb.la = o as u32; } + + let mut l = 1; + let err = (*bins.add(b as usize)).error; + + while l + l <= *heap { + let mut l2 = l + l; + if (l2 < *heap) && ((*bins.add(*heap.add(l2 as usize) as usize)).error > (*bins.add(*heap.add(1 + l2 as usize) as usize)).error) { l2 += 1 } + + let h = *heap.add(l2 as usize); + if err <= (*bins.add(h as usize)).error { break; } + + *heap.add(l as usize) = h; l = l2; + } + + *heap.add(l as usize) = b; + } + + let tb = &mut *bins.add(b as usize); + let nb = &mut *bins.add(tb.nearest as usize); + + let n1 = tb.count; + let n2 = nb.count; + let d = 1.0 / (n1 + n2); + tb.r = d * (n1 * tb.r + n2 * nb.r).round(); + tb.g = d * (n1 * tb.g + n2 * nb.g).round(); + tb.b = d * (n1 * tb.b + n2 * nb.b).round(); + tb.a = d * (n1 * tb.a + n2 * nb.a).round(); + + nb.lb = 0xffff; + tb.count += nb.count; + tb.lb = (o + 1) as u32; + + (*bins.add(nb.p as usize)).n = nb.n; + (*bins.add(nb.n as usize)).p = nb.p; + } + + free(heap as *mut u8, 4 * (1 + BINS)); + let s = if 0 > ext { size } else { colors }; + let palette = alloc(s * size_of!(colors::rgba)) as *mut colors::rgba; + + let mut w = 0; + let mut offset = 0; + + loop { + let r = (*bins.add(offset)).r.clamp(0.0, 255.0) as u8; + let g = (*bins.add(offset)).g.clamp(0.0, 255.0) as u8; + let b = (*bins.add(offset)).b.clamp(0.0, 255.0) as u8; + let a = (*bins.add(offset)).a.clamp(0.0, 255.0) as u8; + + *palette.add(w) = colors::rgba { r, g, b, a }; + + w += 1; + offset = (*bins.add(offset)).n as usize; + + if 0 == offset { break; } + } + + return (s, palette as *mut u32); + } +} \ No newline at end of file diff --git a/v2/index.js b/v2/index.js index 9b9f629..8bcde41 100644 --- a/v2/index.js +++ b/v2/index.js @@ -1,7 +1,7 @@ -const mem = require('./util/mem.js'); +const mem = require('../utils/mem.js'); const png = require('../png/node.js'); const magic = require('./codecs/magic.js'); -const codecs = require('../node/index.js'); +const codecs = require('../codecs/node/index.js'); const { Color, default: framebuffer } = require('./framebuffer.js'); const wasm = { @@ -12,18 +12,20 @@ const wasm = { // font: require('../wasm/node/font.js'), } +// todo: verbose range errors + const animation_formats = ['gif']; const image_formats = ['png', 'jpeg', 'tiff']; const all_formats = ['png', 'gif', 'jpeg', 'tiff']; async function load(buffer) { const u8 = mem.view(buffer); - if (0 === u8.length) throw new TypeError('empty buffer'); + if (0 === u8.length) throw new RangeError('empty buffer'); const meta = magic.buffer(u8); - if (!meta) throw new Error('unknown file format'); - if ('image' !== meta.type) throw new Error('unsupported file type'); - if (!all_formats.includes(meta.format)) throw new Error('unsupported image format'); + if (!meta) throw new RangeError('unknown file format'); + if ('image' !== meta.type) throw new RangeError('unsupported file type'); + if (!all_formats.includes(meta.format)) throw new RangeError('unsupported image format'); if ('gif' === meta.format) return Animation.decode('gif', u8); return Image.from('png' === meta.format ? png.decode(u8) : (await wasm[meta.format].init()).load(u8)); @@ -70,7 +72,7 @@ class Image extends framebuffer { if ('jpeg' === format) return codecs.jpeg[method](this.u8, { ...options, width: this.width, height: this.height }); if ('webp' === format) return codecs.webp[method](this.u8, { ...options, width: this.width, height: this.height }); - throw new TypeError('invalid image format'); + throw new RangeError('invalid image format'); } static async decode(format, buffer, options = {}) { @@ -78,9 +80,9 @@ class Image extends framebuffer { if ('auto' === format) { const meta = magic.buffer(buffer); - if (!meta) throw new Error('unknown file format'); - if ('image' !== meta.type) throw new Error('unsupported file type'); - if (!image_formats.includes(meta.format)) throw new Error('unsupported image format'); + if (!meta) throw new RangeError('unknown file format'); + if ('image' !== meta.type) throw new RangeError('unsupported file type'); + if (!image_formats.includes(meta.format)) throw new RangeError('unsupported image format'); format = meta.format; } @@ -90,7 +92,7 @@ class Image extends framebuffer { else if (format in wasm) frame = (await wasm[format].init()).load(buffer); - if (!frame) throw new TypeError('invalid image format'); + if (!frame) throw new RangeError('invalid image format'); return new Image(frame.width, frame.height, frame.buffer); } } @@ -110,8 +112,8 @@ class Animation { [Symbol.iterator]() { return this.frames.values(); } add(frame) { - if (this.width !== frame.width) throw new Error('invalid frame width'); - else if (this.height !== frame.height) throw new Error('invalid frame height'); + if (this.width !== frame.width) throw new RangeError('invalid frame width'); + else if (this.height !== frame.height) throw new RangeError('invalid frame height'); this.frames.push(frame); } @@ -128,9 +130,7 @@ class Animation { const encoder = new codecs.gif.encoder(this.width, this.height); let prev = { timestamp: 0 }; - for (const frame of this) { - if (!(frame instanceof Frame)) throw new Error('GIF contains invalid frames'); - + for (const frame of this.frames) { encoder.add(frame.image.u8, { x: 0, y: 0, @@ -150,7 +150,7 @@ class Animation { return encoder.finish({ ...options, repeat: Infinity === repeat ? null : repeat }); } - throw new TypeError('invalid image format'); + throw new RangeError('invalid animation format'); } static async decode(format, buffer, options = {}) { @@ -158,9 +158,9 @@ class Animation { if ('auto' === format) { const meta = magic.buffer(buffer); - if (!meta) throw new Error('unknown file format'); - if ('image' !== meta.type) throw new Error('unsupported file type'); - if (!animation_formats.includes(meta.format)) throw new Error('unsupported image format'); + if (!meta) throw new RangeError('unknown file format'); + if ('image' !== meta.type) throw new RangeError('unsupported file type'); + if (!animation_formats.includes(meta.format)) throw new RangeError('unsupported animation format'); format = meta.format; } @@ -254,8 +254,8 @@ class Animation { return animation; } - throw new TypeError('invalid image format'); + throw new RangeError('invalid animation format'); } } -module.exports = { load, Image, Frame, Color, Animation }; \ No newline at end of file +module.exports = { load, Image, Frame, Color, Animation }; diff --git a/v2/ops/blur.js b/v2/ops/blur.mjs similarity index 95% rename from v2/ops/blur.js rename to v2/ops/blur.mjs index af9bc0e..86ba29d 100644 --- a/v2/ops/blur.js +++ b/v2/ops/blur.mjs @@ -30,10 +30,12 @@ export function gaussian(radius, framebuffer) { const a1 = k * g1 * (a - 1); const a2 = k * g1 * (a + 1); const lc = (k + a1) / (1 - b1 - b2); + const width = framebuffer.width | 0; const rc = (a2 + a3) / (1 - b1 - b2); - const tmp = new Float32Array(4 * Math.max(framebuffer.width, framebuffer.height)); - gc(old, framebuffer.u8, tmp, framebuffer.width, framebuffer.height, k, a1, a2, a3, b1, b2, lc, rc); - gc(framebuffer.u8, old, tmp, framebuffer.height, framebuffer.width, k, a1, a2, a3, b1, b2, lc, rc); + const height = framebuffer.height | 0; + const tmp = new Float32Array(4 * Math.max(width, height)); + gc(old, framebuffer.u8, tmp, width, height, k, a1, a2, a3, b1, b2, lc, rc); + gc(framebuffer.u8, old, tmp, height, width, k, a1, a2, a3, b1, b2, lc, rc); } function bb(u8, old, width, height, radius) { @@ -96,6 +98,7 @@ function bbh(u8, old, width, height, radius, divisor) { g += old[1 + offset] - old[1 + roffset]; b += old[2 + offset] - old[2 + roffset]; a += old[3 + offset] - old[3 + roffset]; + // todo: how far is roffset offset = 4 * y_offset++; u8[offset] = Math.round(r * divisor); @@ -176,6 +179,7 @@ function bbt(u8, old, width, height, radius, divisor) { g += old[1 + offset] - old[1 + xoffset]; b += old[2 + offset] - old[2 + xoffset]; a += old[3 + offset] - old[3 + xoffset]; + // todo: how far is xoffset offset = 4 * ti; u8[offset] = Math.round(r * divisor); @@ -211,6 +215,7 @@ function gc(u8, old, tmp, width, height, k, a1, a2, a3, b1, b2, lc, rc) { const width4 = width * 4; const height4 = height * 4; const hw1 = height * (width - 1); + for (let y = 0; y < height; y++) { let toffset = 0 | 0; let ooffset = (y * width4) | 0; diff --git a/v2/ops/color.js b/v2/ops/color.mjs similarity index 100% rename from v2/ops/color.js rename to v2/ops/color.mjs diff --git a/v2/ops/crop.js b/v2/ops/crop.js deleted file mode 100644 index 346f369..0000000 --- a/v2/ops/crop.js +++ /dev/null @@ -1,49 +0,0 @@ -export function cut(x, y, width, height, framebuffer) { - const frame = new framebuffer.constructor(width, height); - - for (let yy = 0; yy < height; yy++) { - const offset = x + (y + yy) * framebuffer.width; - frame.u32.set(framebuffer.u32.subarray(offset, width + offset), yy * width); - } - - return frame; -} - -export function crop(x, y, width, height, framebuffer) { - const old = framebuffer.u32; - framebuffer.u32 = new Uint32Array(width * height); - - for (let yy = 0; yy < height; yy++) { - const offset = x + (y + yy) * framebuffer.width; - framebuffer.u32.set(old.subarray(offset, width + offset), yy * width); - } - - framebuffer.width = width; - framebuffer.height = height; - framebuffer.u8 = new Uint8Array(framebuffer.u32.buffer); - framebuffer.view = new DataView(framebuffer.u32.buffer); -} - -export function circle(feathering, framebuffer) { - const rad = Math.min(framebuffer.width, framebuffer.height) / 2; - - const rad_2 = rad ** 2; - const cx = framebuffer.width / 2; - const cy = framebuffer.height / 2; - const feathering_12 = feathering ** (1 / 2); - - for (let y = 0; y < framebuffer.height; y++) { - const cdy = (y - cy) ** 2; - const y_offset = y * framebuffer.width; - - for (let x = 0; x < framebuffer.width; x++) { - const cd = cdy + (x - cx) ** 2; - const offset = 3 + 4 * (x + y_offset); - - if (cd > rad_2) framebuffer.u8[offset] = 0; - else if (feathering) framebuffer.u8[offset] *= Math.max(0, Math.min(1, 1 - (cd / rad_2) * feathering_12)); - } - } - - return framebuffer; -} \ No newline at end of file diff --git a/v2/ops/crop.mjs b/v2/ops/crop.mjs new file mode 100644 index 0000000..261f529 --- /dev/null +++ b/v2/ops/crop.mjs @@ -0,0 +1,64 @@ +function clamp(min, int, max) { + const t = int < min ? min : int; return t > max ? max : t; +} + +export function cut(x, y, width, height, framebuffer) { + width |= 0; + height |= 0; + const frame = new framebuffer.constructor(width, height); + + const n32 = frame.u32; + const o32 = framebuffer.u32; + const fwidth = framebuffer.width | 0; + + for (let yy = 0 | 0; yy < height; yy++) { + const offset = x + fwidth * (y + yy); + n32.set(o32.subarray(offset, width + offset), yy * width); + } + + return frame; +} + +export function crop(x, y, width, height, framebuffer) { + width |= 0; + height |= 0; + const old = framebuffer.u32; + const fwidth = framebuffer.width | 0; + const u32 = framebuffer.u32 = new Uint32Array(width * height); + + for (let yy = 0; yy < height; yy++) { + const offset = x + fwidth * (y + yy); + u32.set(old.subarray(offset, width + offset), yy * width); + } + + framebuffer.width = width; + framebuffer.height = height; + framebuffer.u8 = new Uint8Array(framebuffer.u32.buffer); + framebuffer.view = new DataView(framebuffer.u32.buffer); +} + +export function circle(feathering, framebuffer) { + const u8 = framebuffer.u8; + const u32 = framebuffer.u32; + const width = framebuffer.width | 0; + const height = framebuffer.height | 0; + const rad = Math.min(width, height) / 2; + + const cx = width / 2; + const cy = height / 2; + const rad_2 = rad ** 2; + const feathering_12 = feathering ** (1 / 2); + + for (let y = 0 | 0; y < height; y++) { + const cdy = (y - cy) ** 2; + const y_offset = y * width; + + for (let x = 0 | 0; x < width; x++) { + const cd = cdy + (x - cx) ** 2; + if (cd > rad_2) u32[x + y_offset] = 0; + else if (feathering) u8[3 + 4 * (x + y_offset)] *= clamp(0, 1 - (cd / rad_2) * feathering_12, 1); + } + } + + return framebuffer; +} \ No newline at end of file diff --git a/v2/ops/fill.js b/v2/ops/fill.mjs similarity index 100% rename from v2/ops/fill.js rename to v2/ops/fill.mjs diff --git a/v2/ops/flip.js b/v2/ops/flip.mjs similarity index 90% rename from v2/ops/flip.js rename to v2/ops/flip.mjs index b8abe0f..6d0902c 100644 --- a/v2/ops/flip.js +++ b/v2/ops/flip.mjs @@ -16,8 +16,8 @@ export function vertical(framebuffer) { const height = (framebuffer.height / 2) | 0; for (let y = 0 | 0; y < height; y++) { - const yo = y * width; - const wo1y = width * (oheight - 1 - y); + const yo = y * width | 0; + const wo1y = width * (oheight - 1 - y) | 0; for (let x = 0 | 0; x < width; x++) { const offset = x + yo; diff --git a/v2/ops/index.js b/v2/ops/index.js deleted file mode 100644 index 396019f..0000000 --- a/v2/ops/index.js +++ /dev/null @@ -1,9 +0,0 @@ -export * as flip from './flip.js'; -export * as fill from './fill.js'; -export * as blur from './blur.js'; -export * as crop from './crop.js'; -export * as color from './color.js'; -export * as resize from './resize.js'; -export * as rotate from './rotate.js'; -export * as overlay from './overlay.js'; -export * as iterator from './iterator.js'; \ No newline at end of file diff --git a/v2/ops/index.mjs b/v2/ops/index.mjs new file mode 100644 index 0000000..dcd9bd6 --- /dev/null +++ b/v2/ops/index.mjs @@ -0,0 +1,9 @@ +export * as flip from './flip.mjs'; +export * as fill from './fill.mjs'; +export * as blur from './blur.mjs'; +export * as crop from './crop.mjs'; +export * as color from './color.mjs'; +export * as resize from './resize.mjs'; +export * as rotate from './rotate.mjs'; +export * as overlay from './overlay.mjs'; +export * as iterator from './iterator.mjs'; \ No newline at end of file diff --git a/v2/ops/iterator.js b/v2/ops/iterator.mjs similarity index 56% rename from v2/ops/iterator.js rename to v2/ops/iterator.mjs index 7c7c683..bd460aa 100644 --- a/v2/ops/iterator.js +++ b/v2/ops/iterator.mjs @@ -1,33 +1,33 @@ -export function *cords(framebuffer) { +export function* cords(framebuffer) { const width = framebuffer.width | 0; const height = framebuffer.height | 0; - for (let y = 1 | 0; y <= height; y++) { - for (let x = 1 | 0; x <= width; x++) yield [x, y]; + for (let y = 0 | 0; y < height; y++) { + for (let x = 0 | 0; x < width; x++) yield [x, y]; } } -export function *rgba(framebuffer) { +export function* rgba(framebuffer) { let offset = 0 | 0; const u8 = framebuffer.u8; const width = framebuffer.width | 0; const height = framebuffer.height | 0; - for (let y = 1 | 0; y <= height; y++) { - for (let x = 1 | 0; x <= width; x++) { + for (let y = 0 | 0; y < height; y++) { + for (let x = 0 | 0; x < width; x++) { yield [x, y, u8.subarray(offset, offset += 4)]; } } } -export function *u32(framebuffer) { +export function* u32(framebuffer) { let offset = 0 | 0; const view = framebuffer.view; const width = framebuffer.width | 0; const height = framebuffer.height | 0; - for (let y = 1 | 0; y <= height; y++) { - for (let x = 1 | 0; x <= width; x++) { + for (let y = 0 | 0; y < height; y++) { + for (let x = 0 | 0; x < width; x++) { yield [x, y, view.getUint32(offset, false)]; offset += 4; } } diff --git a/v2/ops/overlay.js b/v2/ops/overlay.js deleted file mode 100644 index d7ec95d..0000000 --- a/v2/ops/overlay.js +++ /dev/null @@ -1,49 +0,0 @@ -import { blend } from './color.js'; - -export function replace(bg, fg, x, y) { - // TODO: switch to range copying - for (let yy = 0; yy < fg.height; yy++) { - let y_offset = y + yy; - if (y_offset < 0) continue; - if (y_offset >= bg.height) break; - - for (let xx = 0; xx < fg.width; xx++) { - let x_offset = x + xx; - if (x_offset < 0) continue; - if (x_offset >= bg.width) break; - bg.u32[x_offset + y_offset * bg.width] = fg.u32[xx + yy * fg.width]; - } - } -} - -export function overlay(background, foreground, x, y) { - x = x | 0; - y = y | 0; - const fwidth = foreground.width | 0; - const bwidth = background.width | 0; - const fheight = foreground.height | 0; - const bheight = background.height | 0; - - for (let yy = 0 | 0; yy < fheight; yy++) { - let yoffset = y + yy; - if (yoffset < 0) continue; - if (yoffset >= bheight) break; - - yoffset = bwidth * yoffset; - const yyoffset = yy * fwidth; - for (let xx = 0 | 0; xx < fwidth; xx++) { - let xoffset = x + xx; - if (xoffset < 0) continue; - if (xoffset >= bwidth) break; - - const offset = 4 * (xoffset + yoffset); - const fg = foreground.view.getUint32(4 * (xx + yyoffset), false); - - const bg = background.view.getUint32(offset, false); - if ((fg & 0xff) === 0xff) background.view.setUint32(offset, fg, false); - else if ((fg & 0xff) === 0x00) background.view.setUint32(offset, bg, false); - - else background.view.setUint32(offset, blend(fg, bg), false); - } - } -} \ No newline at end of file diff --git a/v2/ops/overlay.mjs b/v2/ops/overlay.mjs new file mode 100644 index 0000000..b0184b1 --- /dev/null +++ b/v2/ops/overlay.mjs @@ -0,0 +1,63 @@ +export function replace(bg, fg, x, y) { + const b32 = bg.u32; + const f32 = fg.u32; + const fw = fg.width | 0; + const bw = bg.width | 0; + const fh = fg.height | 0; + const bh = bg.height | 0; + const ox = (x > 0 ? 0 : -x) | 0; + const oy = (y > 0 ? 0 : -y) | 0; + const top = (y > 0 ? y : 0) | 0; + const left = (x > 0 ? x : 0) | 0; + const width = (Math.min(bw, x + fw) - left) | 0; + const height = (Math.min(bh, y + fh) - top) | 0; + + if (0 >= width || 0 >= height) return; + + for (let yy = 0 | 0; yy < height; yy++) { + const yyoffset = ox + fw * (yy + oy); + const yoffset = left + bw * (yy + top); + b32.subarray(yoffset, width + yoffset).set(f32.subarray(yyoffset, width + yyoffset)); + } +} + +export function blend(bg, fg, x, y) { + const b32 = bg.u32; + const f32 = fg.u32; + const fw = fg.width | 0; + const bw = bg.width | 0; + const fh = fg.height | 0; + const bh = bg.height | 0; + const ox = (x > 0 ? 0 : -x) | 0; + const oy = (y > 0 ? 0 : -y) | 0; + const top = (y > 0 ? y : 0) | 0; + const left = (x > 0 ? x : 0) | 0; + const width = (Math.min(bw, x + fw) - left) | 0; + const height = (Math.min(bh, y + fh) - top) | 0; + + if (0 >= width || 0 >= height) return; + + for (let yy = 0 | 0; yy < height; yy++) { + const yyoffset = ox + fw * (yy + oy); + const yoffset = left + bw * (yy + top); + + for (let xx = 0 | 0; xx < width; xx++) { + const F = f32[xx + yyoffset]; + + // todo: be? + const fa = F >> 24 & 0xff; + if (fa === 0x00) continue; + else if (fa === 0xff) b32[xx + yoffset] = F; + + else { + const alpha = 1 + fa; + const inv_alpha = 256 - fa; + const B = b32[xx + yoffset]; + const r = (alpha * (F & 0xff) + inv_alpha * (B & 0xff)) >> 8; + const g = (alpha * ((F >> 8) & 0xff) + inv_alpha * ((B >> 8) & 0xff)) >> 8; + const b = (alpha * ((F >> 16) & 0xff) + inv_alpha * ((B >> 16) & 0xff)) >> 8; + b32[xx + yoffset] = (Math.max(fa, (B >> 24) & 0xff) << 24) | ((b & 0xff) << 16) | ((g & 0xff) << 8) | r; + } + } + } +} \ No newline at end of file diff --git a/v2/ops/resize.js b/v2/ops/resize.mjs similarity index 97% rename from v2/ops/resize.js rename to v2/ops/resize.mjs index 4be422e..a822037 100644 --- a/v2/ops/resize.js +++ b/v2/ops/resize.mjs @@ -11,9 +11,9 @@ function clamped(x, y, width, height) { } function hermite(A, B, C, D, t) { - const c = (C / 2) + (-A / 2); - const b = A + (2 * C) - (D / 2) - ((5 * B) / 2); - const a = (D / 2) + (-A / 2) + ((3 * B) / 2) - ((3 * C) / 2); + const c = (C / 2) + (A / -2); + const b = A + (C * 2) - (D / 2) - (B * 2.5); + const a = (D / 2) + (A / -2) + (B * 1.5) - (C * 1.5); const t2 = t * t; return B + (c * t) + (b * t2) + (a * t * t2); diff --git a/v2/ops/rotate.js b/v2/ops/rotate.mjs similarity index 88% rename from v2/ops/rotate.js rename to v2/ops/rotate.mjs index c036ead..627ad61 100644 --- a/v2/ops/rotate.js +++ b/v2/ops/rotate.mjs @@ -11,12 +11,12 @@ export function rotate90(framebuffer) { framebuffer.width = height; framebuffer.height = width; - for (let y = 0 | 0; y < width; y++) { + for (let y = 0 | 0; y < height; y++) { const yoffset = y * width; - const height1y = height - 1 - y; + const heighty1 = height - 1 - y; - for (let x = 0 | 0; x < height; x++) { - u32[height1y + x * width] = old[x + yoffset]; + for (let x = 0 | 0; x < width; x++) { + u32[heighty1 + x * height] = old[x + yoffset]; } } } @@ -30,11 +30,11 @@ export function rotate270(framebuffer) { framebuffer.width = height; framebuffer.height = width; - for (let y = 0 | 0; y < width; y++) { + for (let y = 0 | 0; y < height; y++) { const yoffset = y * width; - for (let x = 0 | 0; x < height; x++) { - u32[y + width * (width - 1 - x)] = old[x + yoffset]; + for (let x = 0 | 0; x < width; x++) { + u32[y + height * (width - 1 - x)] = old[x + yoffset]; } } } @@ -84,16 +84,12 @@ function interpolate(inn, out, x0, y0, x1, y1) { const yq = y1 - y2; const offset = 4 * (x0 + y0 * out.width); - const ref = { - r: 0, - g: 0, - b: 0, - a: 0, - }; - + const ref = { r: 0, g: 0, b: 0, a: 0 }; pawn(x2, y2, (1 - xq) * (1 - yq), ref, inn); + pawn(1 + x2, y2, xq * (1 - yq), ref, inn); pawn(x2, 1 + y2, (1 - xq) * yq, ref, inn); + pawn(1 + x2, 1 + y2, xq * yq, ref, inn); out.u8[3 + offset] = ref.a; diff --git a/v2/util/mem.js b/v2/util/mem.mjs similarity index 85% rename from v2/util/mem.js rename to v2/util/mem.mjs index 4a97f47..ce6114e 100644 --- a/v2/util/mem.js +++ b/v2/util/mem.mjs @@ -1,4 +1,4 @@ -function view(buffer, shared = false) { +export function view(buffer, shared = false) { if (buffer instanceof ArrayBuffer) return new Uint8Array(buffer); if (shared && buffer instanceof SharedArrayBuffer) return new Uint8Array(buffer); if (ArrayBuffer.isView(buffer)) return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength); @@ -6,7 +6,7 @@ function view(buffer, shared = false) { throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'"); } -function from_parts(buffers, shared = false) { +export function from_parts(buffers, shared = false) { let length = 0; let offset = 0; buffers.forEach(buffer => length += (null == buffer.byteLength ? buffer.length : buffer.byteLength)); @@ -21,6 +21,4 @@ function from_parts(buffers, shared = false) { }); return u8; -} - -module.exports = { view, from_parts }; \ No newline at end of file +} \ No newline at end of file diff --git a/wasm/any/font.wasm b/wasm/any/font.wasm index a42043e..d8f9097 100755 Binary files a/wasm/any/font.wasm and b/wasm/any/font.wasm differ diff --git a/wasm/any/png.wasm b/wasm/any/png.wasm new file mode 100755 index 0000000..b8ab267 Binary files /dev/null and b/wasm/any/png.wasm differ diff --git a/wasm/node.js b/wasm/node.js deleted file mode 100644 index 0bc984b..0000000 --- a/wasm/node.js +++ /dev/null @@ -1,23 +0,0 @@ -let mod = async () => { - let t; - - { - const simd = WebAssembly.validate(Uint8Array.of(0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,9,1,7,0,65,0,253,15,26,11)); - t = new WebAssembly.Module(await require('fs').promises.readFile(require('path').join(__dirname, `${simd ? 'simd' : 'unknown'}.wasm`))); - } - - return (mod = () => t)(); -}; - -module.exports = async function codecs() { - const wasm = new WebAssembly.Instance(await mod(), {}); - - return { - png: null, - gif: null, - svg: null, - webp: null, - jpeg: null, - tiff: null, - }; -} diff --git a/wasm/node/png.js b/wasm/node/png.js new file mode 100644 index 0000000..911b1a3 --- /dev/null +++ b/wasm/node/png.js @@ -0,0 +1,49 @@ +const wasm_name = 'png'; +const { join } = require('path'); +const { promises: { readFile } } = require('fs'); +const wasm_path = process.env.IMAGESCRIPT_WASM_SIMD ? 'simd' : 'any'; + +let mod = null; +module.exports = { + async init() { + if (!mod) mod = new WebAssembly.Module(await readFile(join(__dirname, `../${wasm_path}/${wasm_name}.wasm`))); + + return this.new(); + }, + + new() { + let u8; + + const { + wfree, walloc, decode, memory, + width: wwidth, height: wheight, + } = new WebAssembly.Instance(mod, { + env: { + emscripten_notify_memory_growth() { + u8 = new Uint8Array(memory.buffer); + }, + }, + }).exports; + + u8 = new Uint8Array(memory.buffer); + + return { + decode(buffer) { + const ptr = walloc(buffer.length); + + u8.set(buffer, ptr); + const status = decode(ptr, buffer.length); + + wfree(ptr); + if (0 > status) throw new Error(`png: failed to decode (${status})`); + + const width = wwidth(); + const height = wheight(); + const framebuffer = u8.slice(status, status + 4 * width * height); + + wfree(status); + return { width, height, framebuffer }; + }, + }; + } +} diff --git a/wasm/web.js b/wasm/web.js deleted file mode 100644 index 95a5b58..0000000 --- a/wasm/web.js +++ /dev/null @@ -1,10 +0,0 @@ -export default async function codecs() { - return { - png: null, - gif: null, - svg: null, - webp: null, - jpeg: null, - tiff: null, - }; -} \ No newline at end of file