// Non-destructive layer styles: drop shadow, outer glow, inner shadow, color overlay // and stroke. They are computed from a layer's final pixels (after the mask, live // strokes and floating pixels) every time the layer is composited, so painting, // moving or masking the layer updates its effects too. // // `layer.effects` is either null or { [effectId]: { enabled, ...params } }. Treat it // as immutable: replace the whole object so history can keep references. import { createCanvas } from '../core/util.js'; import { blendOp } from '../core/layer.js'; const pct = (key, label, def) => ({ key, label, type: 'range', min: 0, max: 100, default: def, unit: '%' }); const px = (key, label, def, min = 0, max = 100) => ({ key, label, type: 'range', min, max, default: def, unit: 'px' }); const angle = (def) => ({ key: 'angle', label: 'Angle', type: 'range', min: -180, max: 180, default: def, unit: '°' }); export const EFFECTS = [ { id: 'dropShadow', label: 'Drop Shadow', params: [{ key: 'color', label: 'Color', type: 'color', default: '#000000' }, pct('opacity', 'Opacity', 60), angle(135), px('distance', 'Distance', 8, 0, 300), px('size', 'Size', 10, 0, 150)], }, { id: 'outerGlow', label: 'Outer Glow', params: [{ key: 'color', label: 'Color', type: 'color', default: '#ffd84a' }, pct('opacity', 'Opacity', 80), pct('spread', 'Spread', 0), px('size', 'Size', 16, 1, 150)], }, { id: 'innerShadow', label: 'Inner Shadow', params: [{ key: 'color', label: 'Color', type: 'color', default: '#000000' }, pct('opacity', 'Opacity', 50), angle(135), px('distance', 'Distance', 5, 0, 300), px('size', 'Size', 6, 0, 150)], }, { id: 'colorOverlay', label: 'Color Overlay', params: [{ key: 'color', label: 'Color', type: 'color', default: '#e5484d' }, pct('opacity', 'Opacity', 100), { key: 'blendMode', label: 'Blend mode', type: 'select', default: 'normal', options: 'blend' }], }, { id: 'stroke', label: 'Stroke', params: [ px('size', 'Size', 3, 1, 100), { key: 'position', label: 'Position', type: 'select', default: 'outside', options: [{ value: 'outside', label: 'Outside' }, { value: 'center', label: 'Center' }, { value: 'inside', label: 'Inside' }], }, { key: 'color', label: 'Color', type: 'color', default: '#000000' }, pct('opacity', 'Opacity', 100), ], }, ]; export const EFFECT_IDS = EFFECTS.map((e) => e.id); /** Settings for one effect with every parameter at its default. */ export function defaultEffect(id) { const spec = EFFECTS.find((e) => e.id === id); const out = { enabled: false }; for (const p of spec.params) out[p.key] = p.default; return out; } /** A complete effects object (all effects present), filled in from `fx`. */ export function normalizeEffects(fx) { const out = {}; for (const id of EFFECT_IDS) out[id] = { ...defaultEffect(id), ...(fx?.[id] || {}) }; return out; } export function hasEffects(layer) { const fx = layer?.effects; return !!fx && EFFECT_IDS.some((id) => fx[id]?.enabled); } /** Labels of the enabled effects (for tooltips and badges). */ export function effectNames(fx) { return EFFECTS.filter((e) => fx?.[e.id]?.enabled).map((e) => e.label); } // ---------------------------------------------------------------- scratch canvases const pool = new Map(); function pooled(name, w, h) { let c = pool.get(name); if (!c) { c = createCanvas(w, h); pool.set(name, c); } if (c.width !== w || c.height !== h) { c.width = w; c.height = h; } const ctx = c.getContext('2d'); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.globalAlpha = 1; ctx.globalCompositeOperation = 'source-over'; ctx.shadowColor = 'transparent'; ctx.filter = 'none'; ctx.clearRect(0, 0, w, h); return c; } function rgba(hex, alpha) { const s = String(hex || '#000000').replace('#', ''); const n = (i) => parseInt(s.slice(i, i + 2), 16) || 0; return `rgba(${n(0)},${n(2)},${n(4)},${Math.max(0, Math.min(1, alpha))})`; } /** Silhouette of `src` (its alpha) filled with a single color. */ function silhouette(name, src, color) { const c = pooled(name, src.width, src.height); const ctx = c.getContext('2d'); ctx.drawImage(src, 0, 0); ctx.globalCompositeOperation = 'source-in'; ctx.fillStyle = color; ctx.fillRect(0, 0, c.width, c.height); ctx.globalCompositeOperation = 'source-over'; return c; } /** * Draw only the (blurred, offset) shadow of `img` onto ctx. The image itself is * drawn far outside the canvas and the shadow offset brings the shadow back. */ function drawShadowOnly(ctx, img, x, y, color, blur, dx, dy) { const far = img.width + ctx.canvas.width + blur * 4 + 256; ctx.save(); ctx.shadowColor = color; ctx.shadowBlur = blur; ctx.shadowOffsetX = dx + far; ctx.shadowOffsetY = dy; ctx.drawImage(img, x - far, y); ctx.restore(); } /** Light angle (degrees, Photoshop convention) and distance to a shadow offset. */ function offsetFor(fx) { const a = (fx.angle * Math.PI) / 180; return { dx: -Math.cos(a) * fx.distance, dy: Math.sin(a) * fx.distance }; } // ---------------------------------------------------------------- distance fields const INF = 1e20; /** 1-D squared distance transform (Felzenszwalb & Huttenlocher). */ function edt1d(f, n, d, v, z) { let k = 0; v[0] = 0; z[0] = -INF; z[1] = INF; for (let q = 1; q < n; q++) { let s = ((f[q] + q * q) - (f[v[k]] + v[k] * v[k])) / (2 * q - 2 * v[k]); while (s <= z[k]) { k--; s = ((f[q] + q * q) - (f[v[k]] + v[k] * v[k])) / (2 * q - 2 * v[k]); } k++; v[k] = q; z[k] = s; z[k + 1] = INF; } k = 0; for (let q = 0; q < n; q++) { while (z[k + 1] < q) k++; const t = q - v[k]; d[q] = t * t + f[v[k]]; } } /** Squared Euclidean distance from every cell to the nearest cell where target[i] === want. */ function distanceTransform(target, w, h, want) { const grid = new Float32Array(w * h); for (let i = 0; i < grid.length; i++) grid[i] = target[i] === want ? 0 : INF; const n = Math.max(w, h); const f = new Float64Array(n), d = new Float64Array(n), v = new Int32Array(n), z = new Float64Array(n + 1); for (let x = 0; x < w; x++) { for (let y = 0, i = x; y < h; y++, i += w) f[y] = grid[i]; edt1d(f, h, d, v, z); for (let y = 0, i = x; y < h; y++, i += w) grid[i] = d[y]; } for (let y = 0; y < h; y++) { const row = y * w; for (let x = 0; x < w; x++) f[x] = grid[row + x]; edt1d(f, w, d, v, z); for (let x = 0; x < w; x++) grid[row + x] = d[x]; } return grid; } /** * Inside/outside distances around the opaque part (alpha >= 128) of src, over its * bounding box grown by `pad`. Pixels beyond the canvas count as transparent. */ function distanceFields(src, pad, needInside) { const w = src.width, h = src.height; const data = src.getContext('2d', { willReadFrequently: true }).getImageData(0, 0, w, h).data; let x0 = w, y0 = h, x1 = -1, y1 = -1; for (let y = 0; y < h; y++) { for (let x = 0, i = y * w * 4 + 3; x < w; x++, i += 4) { if (data[i] >= 128) { if (x < x0) x0 = x; if (x > x1) x1 = x; if (y < y0) y0 = y; if (y > y1) y1 = y; } } } if (x1 < 0) return null; const rx = x0 - pad, ry = y0 - pad, rw = x1 - x0 + 1 + pad * 2, rh = y1 - y0 + 1 + pad * 2; const inside = new Uint8Array(rw * rh); for (let y = 0; y < rh; y++) { const sy = y + ry; if (sy < 0 || sy >= h) continue; for (let x = 0; x < rw; x++) { const sx = x + rx; if (sx >= 0 && sx < w && data[(sy * w + sx) * 4 + 3] >= 128) inside[y * rw + x] = 1; } } return { rx, ry, rw, rh, inside, dOut2: distanceTransform(inside, rw, rh, 1), // squared distance to the shape (0 inside) dIn2: needInside ? distanceTransform(inside, rw, rh, 0) : null, // squared distance to the outside }; } /** * Paint a band around the shape edge in `color` onto a pooled doc-sized canvas. * side 'outside': the shape grown by `radius` (inside included); 'inside': the inner * `radius` px of the shape. Edges get one pixel of anti-aliasing. */ function bandCanvas(name, field, w, h, color, radius, side) { const c = pooled(name, w, h); const { rx, ry, rw, rh, inside } = field; const dist2 = side === 'outside' ? field.dOut2 : field.dIn2; const cx0 = Math.max(0, rx), cy0 = Math.max(0, ry); const cx1 = Math.min(w, rx + rw), cy1 = Math.min(h, ry + rh); if (cx1 <= cx0 || cy1 <= cy0) return c; const s = String(color).replace('#', ''); const r = parseInt(s.slice(0, 2), 16) || 0, g = parseInt(s.slice(2, 4), 16) || 0, b = parseInt(s.slice(4, 6), 16) || 0; const full2 = Math.max(0, radius - 0.5) ** 2, edge2 = (radius + 0.5) ** 2; const ctx = c.getContext('2d'); const ow = cx1 - cx0; const id = ctx.createImageData(ow, cy1 - cy0); const d = id.data; for (let y = cy0; y < cy1; y++) { let i = (y - ry) * rw + (cx0 - rx); let o = (y - cy0) * ow * 4; for (let x = cx0; x < cx1; x++, i++, o += 4) { let a; if (side === 'outside' && inside[i]) a = 255; else if (side === 'inside' && !inside[i]) continue; else { const q = dist2[i]; if (q >= edge2) continue; a = q <= full2 ? 255 : Math.round((radius + 0.5 - Math.sqrt(q)) * 255); if (a <= 0) continue; } d[o] = r; d[o + 1] = g; d[o + 2] = b; d[o + 3] = a; } } ctx.putImageData(id, cx0, cy0); return c; } // ---------------------------------------------------------------- render /** * Render `src` (a layer's final pixels) with its effects into `out` (cleared and * resized to src). Returns `out`. */ export function renderEffects(src, fx, out) { const w = src.width, h = src.height; if (out.width !== w || out.height !== h) { out.width = w; out.height = h; } const ctx = out.getContext('2d'); ctx.save(); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.globalAlpha = 1; ctx.globalCompositeOperation = 'source-over'; ctx.clearRect(0, 0, w, h); const on = (id) => fx?.[id]?.enabled; const stroke = on('stroke') ? fx.stroke : null; const glow = on('outerGlow') ? fx.outerGlow : null; const glowSpread = glow ? (glow.spread / 100) * glow.size : 0; let field = null; if (stroke || glowSpread >= 0.5) { const pad = Math.ceil(Math.max(stroke ? stroke.size : 0, glowSpread)) + 2; field = distanceFields(src, pad, stroke && stroke.position !== 'outside'); } // -- below the layer content if (on('dropShadow')) { const s = fx.dropShadow; const { dx, dy } = offsetFor(s); drawShadowOnly(ctx, src, 0, 0, rgba(s.color, s.opacity / 100), s.size, dx, dy); } if (glow) { const shape = glowSpread >= 0.5 && field ? bandCanvas('fx-glow', field, w, h, '#000000', glowSpread, 'outside') : src; drawShadowOnly(ctx, shape, 0, 0, rgba(glow.color, glow.opacity / 100), Math.max(1, glow.size - glowSpread), 0, 0); } if (stroke && field && stroke.position !== 'inside') { const r = stroke.position === 'center' ? stroke.size / 2 : stroke.size; const ring = bandCanvas('fx-stroke', field, w, h, stroke.color, r, 'outside'); ctx.globalAlpha = stroke.opacity / 100; ctx.drawImage(ring, 0, 0); ctx.globalAlpha = 1; } // -- the content, with overlay and inner shadow applied to it let content = src; if (on('colorOverlay') || on('innerShadow')) { const c = pooled('fx-content', w, h); const cctx = c.getContext('2d'); cctx.drawImage(src, 0, 0); if (on('colorOverlay')) { const o = fx.colorOverlay; if (o.blendMode === 'normal' || !o.blendMode) { cctx.globalCompositeOperation = 'source-atop'; cctx.fillStyle = rgba(o.color, o.opacity / 100); cctx.fillRect(0, 0, w, h); } else { cctx.globalCompositeOperation = blendOp(o.blendMode); cctx.drawImage(silhouette('fx-sil', src, rgba(o.color, o.opacity / 100)), 0, 0); cctx.globalCompositeOperation = 'destination-in'; cctx.drawImage(src, 0, 0); } cctx.globalCompositeOperation = 'source-over'; } if (on('innerShadow')) { const s = fx.innerShadow; const { dx, dy } = offsetFor(s); // The shadow is cast by everything outside the shape, including beyond the canvas. const m = Math.ceil(Math.abs(dx) + Math.abs(dy) + s.size * 2 + 2); const inv = pooled('fx-inv', w + m * 2, h + m * 2); const ictx = inv.getContext('2d'); ictx.fillStyle = '#000'; ictx.fillRect(0, 0, inv.width, inv.height); ictx.globalCompositeOperation = 'destination-out'; ictx.drawImage(src, m, m); ictx.globalCompositeOperation = 'source-over'; const sh = pooled('fx-inner', w, h); const sctx = sh.getContext('2d'); drawShadowOnly(sctx, inv, -m, -m, rgba(s.color, s.opacity / 100), s.size, dx, dy); sctx.globalCompositeOperation = 'destination-in'; sctx.drawImage(src, 0, 0); sctx.globalCompositeOperation = 'source-over'; cctx.globalCompositeOperation = 'source-atop'; cctx.drawImage(sh, 0, 0); cctx.globalCompositeOperation = 'source-over'; } content = c; } ctx.drawImage(content, 0, 0); // -- above the content if (stroke && field && stroke.position !== 'outside') { const r = stroke.position === 'center' ? stroke.size / 2 : stroke.size; const ring = bandCanvas('fx-stroke', field, w, h, stroke.color, r, 'inside'); ctx.globalAlpha = stroke.opacity / 100; ctx.drawImage(ring, 0, 0); } ctx.restore(); return out; }