AI-native design editor. Open-source Figma alternative.
perf(shaders): store opaque shader stills as JPEG (#1107)
Danila Poyarkovf878de3135a4
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 25ae5503a..38312b8f1 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,14 @@## Unreleased+### Fixed++- HTML, Vue, and React exports name a JPEG, GIF, or WebP image fill by its own type in the data URL instead of calling every image PNG.++### Performance++- Shader fills store their still frame as JPEG when no pixel is transparent, about 25 times smaller than PNG, so documents with shaders save and open faster; frames with transparency stay PNG. Figma opens both.+## 0.16.0-beta.2 — 2026-10-12This is a pre-release that lists changes since 0.16.0-beta.1: npm packages are published under the `next` tag, and installed apps on the stable release do not update to it. Linux package managers see `0.16.0-beta.2` as newer than `0.16.0`, so `.deb` and `.rpm` users should remove the beta before installing the final 0.16.0.diff --git a/packages/core/src/editor/shaders/frames.ts b/packages/core/src/editor/shaders/frames.tsindex 111c10475..665f6756b 100644--- a/packages/core/src/editor/shaders/frames.ts+++ b/packages/core/src/editor/shaders/frames.ts@@ -3,6 +3,7 @@ import { isEqual } from 'es-toolkit/predicate'import {isShaderFrameCurrent,readShaderPaints,+ shaderFramePixels,shaderOfPaint,shaderPresetKey,withShaderPaints,@@ -15,10 +16,6 @@ import type { EditorContext, EditorOptions } from '#core/editor/types'import type { ShaderRasterizer } from './types'-/** Frames are drawn at twice the layer's size, for sharp high-density displays. */-const FRAME_SCALE = 2-/** The longest side a frame is drawn at, however large the layer. */-const MAX_FRAME_EDGE = 2048/** How long a layer must keep its size before its frames are drawn again. */const SETTLE_MS = 150@@ -32,15 +29,6 @@ export interface ShaderFramesProgress {/** Fields whose change can leave a shader's frame out of date. */const FRAME_FIELDS = ['fills', 'strokes', 'pluginData', 'width', 'height'] as const-/** The pixels a layer's frame is drawn at. */-function framePixels(size: Size): Size {- const scale = Math.min(FRAME_SCALE, MAX_FRAME_EDGE / Math.max(size.width, size.height, 1))- return {- width: Math.max(1, Math.round(size.width * scale)),- height: Math.max(1, Math.round(size.height * scale))- }-}-const frameKey = (shader: ShaderPaint, size: Size) =>JSON.stringify([shader.preset, Math.round(size.width), Math.round(size.height)])@@ -102,7 +90,7 @@ export function createShaderFrames(const node = graph.getNode(id)if (!node) returnconst size = { width: node.width, height: node.height }- const bytes = await active.render(shader.preset, framePixels(size))+ const bytes = await active.render(shader.preset, shaderFramePixels(size))// The preset, the layer, or the document may have changed while the frame was drawn.const now = graph === ctx.graph ? graph.getNode(id) : undefinedconst current = now && shownShaders(now).find((item) => item.image === shader.image)diff --git a/packages/core/src/editor/shaders/types.ts b/packages/core/src/editor/shaders/types.tsindex b62732d38..ab3a04770 100644--- a/packages/core/src/editor/shaders/types.ts+++ b/packages/core/src/editor/shaders/types.ts@@ -6,7 +6,10 @@ import type { Size } from '@open-pencil/scene-graph/primitives'* one; without it, or where it cannot draw, a shader paint keeps the frame it was saved with.*/export interface ShaderRasterizer {- /** PNG bytes of `preset`'s first frame at `size` pixels, or null when it cannot draw here. */+ /**+ * `preset`'s first frame at `size` pixels, encoded as `shaderFrameEncoding` picks, or null+ * when it cannot draw here.+ */render(preset: ShaderPreset, size: Size): Promise<Uint8Array | null>destroy?(): void}diff --git a/packages/core/src/io/formats/svg/defs.ts b/packages/core/src/io/formats/svg/defs.tsindex f475522cd..c6cd2772f 100644--- a/packages/core/src/io/formats/svg/defs.ts+++ b/packages/core/src/io/formats/svg/defs.ts@@ -1,6 +1,12 @@import { fromUint8Array } from 'js-base64'-import type { Effect, Fill, SceneGraph, SceneNode } from '@open-pencil/scene-graph'+import {+ imageMimeType,+ type Effect,+ type Fill,+ type SceneGraph,+ type SceneNode+} from '@open-pencil/scene-graph'import {colorToHex,colorToDisplayCSS,@@ -133,7 +139,7 @@ function createImagePattern(const id = nextDefId(ctx, 'img')const base64 = fromUint8Array(data)- const mime = detectImageMime(data)+ const mime = imageMimeType(data)return {id,@@ -155,13 +161,6 @@ function createImagePattern(}}-function detectImageMime(data: Uint8Array): string {- if (data[0] === 0x89 && data[1] === 0x50) return 'image/png'- if (data[0] === 0xff && data[1] === 0xd8) return 'image/jpeg'- if (data[0] === 0x52 && data[1] === 0x49) return 'image/webp'- return 'image/png'-}-export function createFilterDef(effects: Effect[],ctx: SVGExportContextdiff --git a/packages/dom-css/src/export/projection.ts b/packages/dom-css/src/export/projection.tsindex 08e3c6589..e28286edc 100644--- a/packages/dom-css/src/export/projection.ts+++ b/packages/dom-css/src/export/projection.ts@@ -1,6 +1,7 @@import { fromUint8Array } from 'js-base64'import {+ imageMimeType,layoutSizingInParent,readIcon,shaderOfPaint,@@ -234,6 +235,11 @@ function addFlexGap(style: DesignStyleDeclaration, node: SceneNode, css: FieldCSstyle['column-gap'] = counter}+/** Image bytes as a data URL of the type they are encoded in. */+function imageDataURL(bytes: Uint8Array): string {+ return `data:${imageMimeType(bytes)};base64,${fromUint8Array(bytes)}`+}+/*** The shader a layer's fill draws, which the projection keeps as the shader rather than the* image of its still frame: the shader of its first fill, as the projection reads one fill.@@ -243,7 +249,7 @@ function layerShader(graph: SceneGraph, node: SceneNode): DesignElement['shader'const shader = fill?.visible ? shaderOfPaint(node, fill) : nullif (!shader) return undefinedconst bytes = graph.images.get(shader.image)- const frame = bytes ? `data:image/png;base64,${fromUint8Array(bytes)}` : undefined+ const frame = bytes ? imageDataURL(bytes) : undefinedreturn { preset: shader.preset, frame }}@@ -392,7 +398,7 @@ function attrsForNode(if (fill?.type !== 'IMAGE' || !fill.imageHash || shaderOfPaint(node, fill)) return attrsconst bytes = graph.images.get(fill.imageHash)if (!bytes) return attrs- return { ...attrs, src: `data:image/png;base64,${fromUint8Array(bytes)}` }+ return { ...attrs, src: imageDataURL(bytes) }}function tagNameForNode(node: SceneNode): string {diff --git a/packages/dom-css/tests/export/shaders.test.ts b/packages/dom-css/tests/export/shaders.test.tsindex c251863da..a65443374 100644--- a/packages/dom-css/tests/export/shaders.test.ts+++ b/packages/dom-css/tests/export/shaders.test.ts@@ -12,12 +12,13 @@ const PRESET = {components: [{ type: 'Aurora', props: { colorA: '#ff3300', speed: 2 } }, { type: 'FilmGrain' }]}const FRAME = new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10])+const JPEG_FRAME = new Uint8Array([0xff, 0xd8, 0xff, 0xe0, 0, 16, 74, 70, 73, 70])/** A layer with no children that fills with a shader, whose still frame is saved. */-function shaderLayer() {+function shaderLayer(frame = FRAME) {const graph = new SceneGraph()const { paint, shader } = createShaderPaint(PRESET)- graph.images.set(shader.image, FRAME)+ graph.images.set(shader.image, frame)const node = graph.createNode('RECTANGLE', graph.getPages()[0].id, {name: 'Glow',width: 200,@@ -52,4 +53,11 @@ describe('shader fills in DOM exports', () => {/^<div[^>]*><img src="data:image\/png;base64,[^"]+" alt="" style="[^"]*z-index:-1/)})++ test('static HTML names an opaque still frame saved as JPEG as JPEG', () => {+ const { graph, id } = shaderLayer(JPEG_FRAME)+ const html = serializeHTML(sceneNodeToDesignDocument(graph, id))++ expect(html).toContain('<img src="data:image/jpeg;base64,')+ })})diff --git a/packages/scene-graph/src/images.ts b/packages/scene-graph/src/images.tsindex 016e34b3b..3b40225f4 100644--- a/packages/scene-graph/src/images.ts+++ b/packages/scene-graph/src/images.ts@@ -32,3 +32,18 @@ export function computeImageHash(data: Uint8Array): string {h5 = Math.imul(h5 ^ data.length, 0x01000193) >>> 0return [h1, h2, h3, h4, h5].map((hash) => hash.toString(16).padStart(8, '0')).join('')}++export type ImageMimeType = 'image/png' | 'image/jpeg' | 'image/gif' | 'image/webp'++/**+ * The media type of encoded image bytes, read from their signature, for writing them out as a+ * data URL or file. Bytes with no known signature are reported as PNG, as image fills began.+ */+export function imageMimeType(data: Uint8Array): ImageMimeType {+ if (data[0] === 0xff && data[1] === 0xd8 && data[2] === 0xff) return 'image/jpeg'+ if (data[0] === 0x47 && data[1] === 0x49 && data[2] === 0x46) return 'image/gif'+ const riff = data[0] === 0x52 && data[1] === 0x49 && data[2] === 0x46 && data[3] === 0x46+ const webp = data[8] === 0x57 && data[9] === 0x45 && data[10] === 0x42 && data[11] === 0x50+ if (riff && webp) return 'image/webp'+ return 'image/png'+}diff --git a/packages/scene-graph/src/index.ts b/packages/scene-graph/src/index.tsindex dd20cbd41..ce6469578 100644--- a/packages/scene-graph/src/index.ts+++ b/packages/scene-graph/src/index.ts@@ -33,6 +33,7 @@ export * from './icons/model'export * from './icons/glyph'export * from './shaders/schema'export * from './shaders/model'+export * from './shaders/still'export * from './behaviours/layers'export * from './behaviours/model'export * from './behaviours/spec'diff --git a/packages/scene-graph/src/shaders/still.ts b/packages/scene-graph/src/shaders/still.tsnew file mode 100644index 000000000..e3981bbaf--- /dev/null+++ b/packages/scene-graph/src/shaders/still.ts@@ -0,0 +1,41 @@+import type { Size } from '../primitives'++/**+ * How a shader paint's still frame is drawn and stored, for every renderer that draws one: the+ * editor's canvas and the tools that prebuild documents. The frame is an image fill in `.fig`+ * files, so Figma must be able to read it, which rules out WebP.+ */++/** Frames are drawn at twice the layer's size, for sharp high-density displays. */+const FRAME_SCALE = 2+/** The longest side a frame is drawn at, however large the layer. */+const MAX_FRAME_EDGE = 2048+/** JPEG quality for opaque frames: no visible difference from PNG at a fraction of the size. */+const JPEG_QUALITY = 0.9++/** The pixels a frame for a layer of `size` is drawn at. */+export function shaderFramePixels(size: Size): Size {+ const scale = Math.min(FRAME_SCALE, MAX_FRAME_EDGE / Math.max(size.width, size.height, 1))+ return {+ width: Math.max(1, Math.round(size.width * scale)),+ height: Math.max(1, Math.round(size.height * scale))+ }+}++export interface ShaderFrameEncoding {+ type: 'image/jpeg' | 'image/png'+ /** For `canvas.toBlob` and `toDataURL`; PNG takes none. */+ quality?: number+}++/**+ * The encoding a frame with these RGBA pixels is stored in: JPEG when every pixel is opaque, which+ * is about 25 times smaller than PNG for a shader, and PNG when any pixel lets the layer behind+ * show through, which JPEG cannot keep.+ */+export function shaderFrameEncoding(rgba: ArrayLike<number>): ShaderFrameEncoding {+ for (let alpha = 3; alpha < rgba.length; alpha += 4) {+ if (rgba[alpha] !== 255) return { type: 'image/png' }+ }+ return { type: 'image/jpeg', quality: JPEG_QUALITY }+}diff --git a/packages/scene-graph/tests/images.test.ts b/packages/scene-graph/tests/images.test.tsnew file mode 100644index 000000000..7bcbdc54b--- /dev/null+++ b/packages/scene-graph/tests/images.test.ts@@ -0,0 +1,19 @@+import { describe, expect, test } from 'bun:test'++import { imageMimeType } from '@open-pencil/scene-graph'++describe('imageMimeType', () => {+ test('reads the type from the bytes', () => {+ expect(imageMimeType(new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))).toBe(+ 'image/png'+ )+ expect(imageMimeType(new Uint8Array([0xff, 0xd8, 0xff, 0xe0]))).toBe('image/jpeg')+ expect(imageMimeType(new TextEncoder().encode('GIF89a'))).toBe('image/gif')+ expect(imageMimeType(new TextEncoder().encode('RIFF\0\0\0\0WEBPVP8 '))).toBe('image/webp')+ })++ test('reports bytes with no known signature as PNG', () => {+ expect(imageMimeType(new TextEncoder().encode('RIFF\0\0\0\0WAVEfmt '))).toBe('image/png')+ expect(imageMimeType(new Uint8Array())).toBe('image/png')+ })+})diff --git a/packages/scene-graph/tests/shaders/still.test.ts b/packages/scene-graph/tests/shaders/still.test.tsnew file mode 100644index 000000000..457316aa1--- /dev/null+++ b/packages/scene-graph/tests/shaders/still.test.ts@@ -0,0 +1,27 @@+import { describe, expect, test } from 'bun:test'++import { shaderFrameEncoding, shaderFramePixels } from '@open-pencil/scene-graph'++/** RGBA pixels with every alpha set to `alpha`. */+function pixels(count: number, alpha: number): Uint8ClampedArray {+ const data = new Uint8ClampedArray(count * 4).fill(128)+ for (let index = 3; index < data.length; index += 4) data[index] = alpha+ return data+}++describe('shader still frames', () => {+ test('are drawn at twice the layer size, up to a 2048 pixel edge', () => {+ expect(shaderFramePixels({ width: 320, height: 160 })).toEqual({ width: 640, height: 320 })+ expect(shaderFramePixels({ width: 2000, height: 1000 })).toEqual({ width: 2048, height: 1024 })+ })++ test('are stored as JPEG when every pixel is opaque', () => {+ expect(shaderFrameEncoding(pixels(16, 255))).toEqual({ type: 'image/jpeg', quality: 0.9 })+ })++ test('are stored as PNG when any pixel lets the layer behind show through', () => {+ const data = pixels(16, 255)+ data[4 * 9 + 3] = 254+ expect(shaderFrameEncoding(data)).toEqual({ type: 'image/png' })+ })+})diff --git a/packages/vue/src/canvas/surface/shader/rasterizer.ts b/packages/vue/src/canvas/surface/shader/rasterizer.tsindex 231603db0..24cea14bc 100644--- a/packages/vue/src/canvas/surface/shader/rasterizer.ts+++ b/packages/vue/src/canvas/surface/shader/rasterizer.ts@@ -1,4 +1,5 @@import type { ShaderRasterizer } from '@open-pencil/core/editor'+import { shaderFrameEncoding } from '@open-pencil/scene-graph'/** Whether this browser can draw shaders, which need WebGPU. */export function canDrawShaders(): boolean {@@ -9,9 +10,27 @@ export function canDrawShaders(): boolean {return gpu !== undefined}+/**+ * The drawn frame on `canvas`, encoded as its pixels call for. A WebGPU canvas has no pixels to+ * read, so the frame is copied to a 2D canvas first, and encoded from there.+ */+async function encodeFrame(canvas: HTMLCanvasElement): Promise<Blob | null> {+ const copy = document.createElement('canvas')+ copy.width = canvas.width+ copy.height = canvas.height+ const context = copy.getContext('2d')+ if (!context) return null+ context.drawImage(canvas, 0, 0)+ const { data } = context.getImageData(0, 0, copy.width, copy.height)+ const { type, quality } = shaderFrameEncoding(data)+ return new Promise<Blob | null>((resolve) => {+ copy.toBlob(resolve, type, quality)+ })+}+/*** Draws shader frames with the `shaders` library's preset renderer on a detached WebGPU canvas,- * one at a time, and encodes each as PNG. The library is loaded on the first frame, so documents+ * one at a time, and encodes each as `shaderFrameEncoding` picks from its pixels. The library is loaded on the first frame, so documents* without shaders never fetch it. Null where the browser has no WebGPU.*/export function createShaderRasterizer(): ShaderRasterizer | null {@@ -35,10 +54,7 @@ export function createShaderRasterizer(): ShaderRasterizer | null {// pipelines, so the one kept is the second; reading the canvas waits for the GPU.await renderer.renderFrame({ deltaSeconds: 0, waitForGpu: false })await renderer.renderFrame({ deltaSeconds: 0, waitForGpu: false })- const encoded = new Promise<Blob | null>((resolve) => {- canvas.toBlob(resolve, 'image/png')- })- const blob = await encoded+ const blob = await encodeFrame(canvas)if (isDestroyed() || !blob) return nullconst bytes = new Uint8Array(await blob.arrayBuffer())return isDestroyed() ? null : bytesdiff --git a/packages/vue/src/controls/shader/preview.ts b/packages/vue/src/controls/shader/preview.tsindex 3808c7a84..1c12d3a78 100644--- a/packages/vue/src/controls/shader/preview.ts+++ b/packages/vue/src/controls/shader/preview.ts@@ -1,4 +1,4 @@-import type { ShaderPreset } from '@open-pencil/scene-graph'+import { imageMimeType, type ShaderPreset } from '@open-pencil/scene-graph'import { createShaderRasterizer } from '#vue/canvas/surface/shader/rasterizer'@@ -36,7 +36,7 @@ export function shaderEffectPreview(effect: ShaderEffect): Promise<string | nullheight: PREVIEW_SIZE.height * ratio})return bytes- ? URL.createObjectURL(new Blob([new Uint8Array(bytes)], { type: 'image/png' }))+ ? URL.createObjectURL(new Blob([new Uint8Array(bytes)], { type: imageMimeType(bytes) })): null})// A preview that fails to draw leaves the rest of the queue to go on.diff --git a/tools/generate/demo/src/shaders/page.ts b/tools/generate/demo/src/shaders/page.tsindex 32a8695f8..770a6e701 100644--- a/tools/generate/demo/src/shaders/page.ts+++ b/tools/generate/demo/src/shaders/page.ts@@ -1,10 +1,11 @@/*** The page `drawShaderStills` opens in a browser: it draws a shader preset's first frame on a- * WebGPU canvas and hands it back as a PNG data URL. Bundled for the browser at build time.+ * WebGPU canvas and hands it back as a data URL, encoded as the editor encodes frames+ * (`shaderFrameEncoding`). Bundled for the browser at build time.*/import { createRendererFromJSON } from 'shaders/core'-import type { ShaderPreset } from '@open-pencil/scene-graph'+import { shaderFrameEncoding, type ShaderPreset } from '@open-pencil/scene-graph'export interface ShaderStillPage {renderStill(preset: ShaderPreset, width: number, height: number): Promise<string>@@ -21,7 +22,17 @@ const page: ShaderStillPage = {// The first frame only prepares the effects' pipelines; the second is the still.await renderer.renderFrame({ deltaSeconds: 0, waitForGpu: false })await renderer.renderFrame({ deltaSeconds: 0, waitForGpu: false })- return canvas.toDataURL('image/png')+ // A WebGPU canvas has no pixels to read; a 2D copy does.+ const copy = document.createElement('canvas')+ copy.width = canvas.width+ copy.height = canvas.height+ const context = copy.getContext('2d')+ if (!context) throw new Error('No 2D canvas to encode the frame')+ context.drawImage(canvas, 0, 0)+ const { type, quality } = shaderFrameEncoding(+ context.getImageData(0, 0, copy.width, copy.height).data+ )+ return copy.toDataURL(type, quality)} finally {renderer.dispose()}diff --git a/tools/generate/demo/src/shaders/stills.ts b/tools/generate/demo/src/shaders/stills.tsindex 62c65c17b..2888acea8 100644--- a/tools/generate/demo/src/shaders/stills.ts+++ b/tools/generate/demo/src/shaders/stills.ts@@ -5,6 +5,7 @@ import { toUint8Array } from 'js-base64'import {isShaderFrameCurrent,+ shaderFramePixels,shaderOfPaint,shaderPresetKey,withShaderPaints,@@ -15,10 +16,6 @@ import {import type { ShaderStillPage } from './page'-/** Frames are drawn at twice the layer's size, as the editor draws them, up to this edge. */-const FRAME_SCALE = 2-const MAX_FRAME_EDGE = 1600-/** Headless Chromium has WebGPU only with SwiftShader, and only on a secure origin. */const BROWSER_ARGS = ['--enable-unsafe-webgpu',@@ -41,14 +38,6 @@ function staleShaders(graph: SceneGraph, node: SceneNode): ShaderPaint[] {})}-function framePixels(node: SceneNode): { width: number; height: number } {- const scale = Math.min(FRAME_SCALE, MAX_FRAME_EDGE / Math.max(node.width, node.height, 1))- return {- width: Math.max(1, Math.round(node.width * scale)),- height: Math.max(1, Math.round(node.height * scale))- }-}-/** The still page as one HTML document and its script, served from a loopback port. */async function serveStillPage() {const built = await Bun.build({@@ -92,7 +81,7 @@ export async function drawShaderStills(graph: SceneGraph): Promise<number> {await page.goto(`http://127.0.0.1:${server.port}/`)await page.waitForFunction(() => Reflect.has(window, 'shaderStill'))for (const { node, shader } of jobs) {- const pixels = framePixels(node)+ const pixels = shaderFramePixels(node)// Runs in the page, so the check is written out here rather than shared.const dataURL = await page.evaluate(({ preset, width, height }) => {