Skip to content

OpenReel Video - Professional browser-based video editor. Open source CapCut alternative. 100% browser-based, no installation, no cloud uploads, no watermarks.

TypeScript

feat(image): add Phase 2 retouching and paint tools

Augustus Otu13bd994489d4
diff --git a/apps/image/src/tools/brush/brush-engine.ts b/apps/image/src/tools/brush/brush-engine.ts
new file mode 100644
index 00000000..7b025f98
--- /dev/null
+++ b/apps/image/src/tools/brush/brush-engine.ts
@@ -0,0 +1,362 @@
+export type DynamicsControl = 'off' | 'fade' | 'pen-pressure' | 'pen-tilt' | 'rotation';
+
+export interface BrushDynamics {
+ control: DynamicsControl;
+ minValue: number;
+ jitter: number;
+}
+
+export interface BrushSettings {
+ size: number;
+ hardness: number;
+ opacity: number;
+ flow: number;
+ spacing: number;
+ angle: number;
+ roundness: number;
+
+ sizeDynamics: BrushDynamics;
+ opacityDynamics: BrushDynamics;
+ flowDynamics: BrushDynamics;
+
+ tip: 'round' | 'square' | 'custom';
+ customTip: ImageData | null;
+
+ buildUp: boolean;
+ smoothing: number;
+}
+
+export const DEFAULT_BRUSH_DYNAMICS: BrushDynamics = {
+ control: 'off',
+ minValue: 0,
+ jitter: 0,
+};
+
+export const DEFAULT_BRUSH_SETTINGS: BrushSettings = {
+ size: 20,
+ hardness: 100,
+ opacity: 1,
+ flow: 1,
+ spacing: 25,
+ angle: 0,
+ roundness: 100,
+
+ sizeDynamics: { ...DEFAULT_BRUSH_DYNAMICS },
+ opacityDynamics: { ...DEFAULT_BRUSH_DYNAMICS },
+ flowDynamics: { ...DEFAULT_BRUSH_DYNAMICS },
+
+ tip: 'round',
+ customTip: null,
+
+ buildUp: false,
+ smoothing: 50,
+};
+
+export interface BrushStroke {
+ points: Array<{
+ x: number;
+ y: number;
+ pressure: number;
+ tilt: { x: number; y: number };
+ timestamp: number;
+ }>;
+ color: string;
+ settings: BrushSettings;
+}
+
+export interface StrokePoint {
+ x: number;
+ y: number;
+ pressure: number;
+ tilt?: { x: number; y: number };
+}
+
+export class BrushEngine {
+ private canvas: OffscreenCanvas;
+ private ctx: OffscreenCanvasRenderingContext2D;
+ private brushCache: Map<string, ImageData> = new Map();
+
+ constructor(width: number, height: number) {
+ this.canvas = new OffscreenCanvas(width, height);
+ this.ctx = this.canvas.getContext('2d', { willReadFrequently: true })!;
+ }
+
+ resize(width: number, height: number): void {
+ this.canvas = new OffscreenCanvas(width, height);
+ this.ctx = this.canvas.getContext('2d', { willReadFrequently: true })!;
+ }
+
+ createBrushTip(settings: BrushSettings): ImageData {
+ const cacheKey = `${settings.size}-${settings.hardness}-${settings.tip}-${settings.angle}-${settings.roundness}`;
+ const cached = this.brushCache.get(cacheKey);
+ if (cached) return cached;
+
+ const size = Math.ceil(settings.size);
+ const tipCanvas = new OffscreenCanvas(size, size);
+ const tipCtx = tipCanvas.getContext('2d')!;
+
+ const center = size / 2;
+ const radius = size / 2;
+
+ if (settings.tip === 'square') {
+ tipCtx.fillStyle = 'white';
+ tipCtx.save();
+ tipCtx.translate(center, center);
+ tipCtx.rotate((settings.angle * Math.PI) / 180);
+ tipCtx.scale(1, settings.roundness / 100);
+ tipCtx.fillRect(-radius, -radius, size, size);
+ tipCtx.restore();
+ } else if (settings.tip === 'custom' && settings.customTip) {
+ tipCtx.putImageData(settings.customTip, 0, 0);
+ } else {
+ const hardness = settings.hardness / 100;
+
+ tipCtx.save();
+ tipCtx.translate(center, center);
+ tipCtx.rotate((settings.angle * Math.PI) / 180);
+ tipCtx.scale(1, settings.roundness / 100);
+
+ if (hardness >= 0.99) {
+ tipCtx.beginPath();
+ tipCtx.arc(0, 0, radius, 0, Math.PI * 2);
+ tipCtx.fillStyle = 'white';
+ tipCtx.fill();
+ } else {
+ const gradient = tipCtx.createRadialGradient(0, 0, 0, 0, 0, radius);
+ const hardnessPoint = Math.max(0.01, hardness);
+ gradient.addColorStop(0, 'rgba(255, 255, 255, 1)');
+ gradient.addColorStop(hardnessPoint, 'rgba(255, 255, 255, 1)');
+ gradient.addColorStop(1, 'rgba(255, 255, 255, 0)');
+
+ tipCtx.fillStyle = gradient;
+ tipCtx.fillRect(-radius, -radius, size, size);
+ }
+
+ tipCtx.restore();
+ }
+
+ const imageData = tipCtx.getImageData(0, 0, size, size);
+
+ if (this.brushCache.size > 50) {
+ const firstKey = this.brushCache.keys().next().value;
+ if (firstKey) this.brushCache.delete(firstKey);
+ }
+ this.brushCache.set(cacheKey, imageData);
+
+ return imageData;
+ }
+
+ applyDynamics(
+ baseValue: number,
+ dynamics: BrushDynamics,
+ pressure: number,
+ _tilt: { x: number; y: number },
+ fadeProgress: number
+ ): number {
+ let value = baseValue;
+
+ switch (dynamics.control) {
+ case 'pen-pressure':
+ value = dynamics.minValue + (baseValue - dynamics.minValue) * pressure;
+ break;
+ case 'fade':
+ value = dynamics.minValue + (baseValue - dynamics.minValue) * (1 - fadeProgress);
+ break;
+ case 'pen-tilt':
+ value = dynamics.minValue + (baseValue - dynamics.minValue) * pressure;
+ break;
+ case 'rotation':
+ break;
+ case 'off':
+ default:
+ break;
+ }
+
+ if (dynamics.jitter > 0) {
+ const jitterAmount = (Math.random() - 0.5) * 2 * dynamics.jitter * baseValue;
+ value += jitterAmount;
+ }
+
+ return Math.max(0, value);
+ }
+
+ drawStroke(
+ targetCtx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D,
+ stroke: BrushStroke,
+ startIndex: number = 0
+ ): void {
+ const { points, color, settings } = stroke;
+ if (points.length < 2) return;
+
+ const totalLength = this.calculateStrokeLength(points);
+ const spacingPx = (settings.size * settings.spacing) / 100;
+
+ let accumulatedDistance = 0;
+ let currentLength = 0;
+
+ for (let i = Math.max(1, startIndex); i < points.length; i++) {
+ const prev = points[i - 1];
+ const curr = points[i];
+
+ const dx = curr.x - prev.x;
+ const dy = curr.y - prev.y;
+ const segmentLength = Math.sqrt(dx * dx + dy * dy);
+
+ if (segmentLength < 0.1) continue;
+
+ const steps = Math.ceil(segmentLength / spacingPx);
+ for (let step = 0; step < steps; step++) {
+ const t = step / steps;
+ const x = prev.x + dx * t;
+ const y = prev.y + dy * t;
+
+ const pressure = prev.pressure + (curr.pressure - prev.pressure) * t;
+ const tilt = {
+ x: prev.tilt.x + (curr.tilt.x - prev.tilt.x) * t,
+ y: prev.tilt.y + (curr.tilt.y - prev.tilt.y) * t,
+ };
+ const fadeProgress = currentLength / totalLength;
+
+ const dynamicSize = this.applyDynamics(
+ settings.size,
+ settings.sizeDynamics,
+ pressure,
+ tilt,
+ fadeProgress
+ );
+ const dynamicOpacity = this.applyDynamics(
+ settings.opacity,
+ settings.opacityDynamics,
+ pressure,
+ tilt,
+ fadeProgress
+ );
+ const dynamicFlow = this.applyDynamics(
+ settings.flow,
+ settings.flowDynamics,
+ pressure,
+ tilt,
+ fadeProgress
+ );
+
+ this.drawDab(targetCtx, x, y, color, {
+ ...settings,
+ size: dynamicSize,
+ opacity: dynamicOpacity,
+ flow: dynamicFlow,
+ });
+
+ accumulatedDistance += spacingPx;
+ currentLength += spacingPx;
+ }
+ }
+ }
+
+ drawDab(
+ ctx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D,
+ x: number,
+ y: number,
+ color: string,
+ settings: BrushSettings
+ ): void {
+ const size = Math.max(1, Math.round(settings.size));
+ const halfSize = size / 2;
+
+ ctx.save();
+ ctx.globalAlpha = settings.opacity * settings.flow;
+
+ if (settings.tip === 'square') {
+ ctx.translate(x, y);
+ ctx.rotate((settings.angle * Math.PI) / 180);
+ ctx.scale(1, settings.roundness / 100);
+ ctx.fillStyle = color;
+ ctx.fillRect(-halfSize, -halfSize, size, size);
+ } else {
+ const hardness = settings.hardness / 100;
+
+ ctx.translate(x, y);
+ ctx.rotate((settings.angle * Math.PI) / 180);
+ ctx.scale(1, settings.roundness / 100);
+
+ if (hardness >= 0.99) {
+ ctx.beginPath();
+ ctx.arc(0, 0, halfSize, 0, Math.PI * 2);
+ ctx.fillStyle = color;
+ ctx.fill();
+ } else {
+ const gradient = ctx.createRadialGradient(0, 0, 0, 0, 0, halfSize);
+ const rgba = this.hexToRgba(color);
+ const hardnessPoint = Math.max(0.01, hardness);
+
+ gradient.addColorStop(0, `rgba(${rgba.r}, ${rgba.g}, ${rgba.b}, 1)`);
+ gradient.addColorStop(hardnessPoint, `rgba(${rgba.r}, ${rgba.g}, ${rgba.b}, 1)`);
+ gradient.addColorStop(1, `rgba(${rgba.r}, ${rgba.g}, ${rgba.b}, 0)`);
+
+ ctx.fillStyle = gradient;
+ ctx.fillRect(-halfSize, -halfSize, size, size);
+ }
+ }
+
+ ctx.restore();
+ }
+
+ private calculateStrokeLength(points: BrushStroke['points']): number {
+ let length = 0;
+ for (let i = 1; i < points.length; i++) {
+ const dx = points[i].x - points[i - 1].x;
+ const dy = points[i].y - points[i - 1].y;
+ length += Math.sqrt(dx * dx + dy * dy);
+ }
+ return length;
+ }
+
+ private hexToRgba(hex: string): { r: number; g: number; b: number; a: number } {
+ const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
+ if (result) {
+ return {
+ r: parseInt(result[1], 16),
+ g: parseInt(result[2], 16),
+ b: parseInt(result[3], 16),
+ a: 1,
+ };
+ }
+ return { r: 0, g: 0, b: 0, a: 1 };
+ }
+
+ smoothPoints(points: StrokePoint[], smoothing: number): StrokePoint[] {
+ if (points.length < 3 || smoothing <= 0) return points;
+
+ const factor = smoothing / 100;
+ const smoothed: StrokePoint[] = [points[0]];
+
+ for (let i = 1; i < points.length - 1; i++) {
+ const prev = points[i - 1];
+ const curr = points[i];
+ const next = points[i + 1];
+
+ smoothed.push({
+ x: curr.x * (1 - factor) + ((prev.x + next.x) / 2) * factor,
+ y: curr.y * (1 - factor) + ((prev.y + next.y) / 2) * factor,
+ pressure: curr.pressure,
+ tilt: curr.tilt,
+ });
+ }
+
+ smoothed.push(points[points.length - 1]);
+ return smoothed;
+ }
+
+ getCanvas(): OffscreenCanvas {
+ return this.canvas;
+ }
+
+ getContext(): OffscreenCanvasRenderingContext2D {
+ return this.ctx;
+ }
+
+ clear(): void {
+ this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
+ }
+}
+
+export const brushEngine = new BrushEngine(1920, 1080);
diff --git a/apps/image/src/tools/brush/brush-presets.ts b/apps/image/src/tools/brush/brush-presets.ts
new file mode 100644
index 00000000..777929dd
--- /dev/null
+++ b/apps/image/src/tools/brush/brush-presets.ts
@@ -0,0 +1,453 @@
+import { BrushSettings, DEFAULT_BRUSH_SETTINGS } from './brush-engine';
+
+export interface BrushPreset {
+ id: string;
+ name: string;
+ category: BrushCategory;
+ settings: BrushSettings;
+ thumbnail?: string;
+}
+
+export type BrushCategory =
+ | 'general'
+ | 'soft'
+ | 'hard'
+ | 'texture'
+ | 'special'
+ | 'artistic'
+ | 'custom';
+
+export const BRUSH_PRESETS: BrushPreset[] = [
+ {
+ id: 'soft-round',
+ name: 'Soft Round',
+ category: 'soft',
+ settings: {
+ ...DEFAULT_BRUSH_SETTINGS,
+ size: 30,
+ hardness: 0,
+ opacity: 1,
+ flow: 1,
+ spacing: 25,
+ tip: 'round',
+ },
+ },
+ {
+ id: 'hard-round',
+ name: 'Hard Round',
+ category: 'hard',
+ settings: {
+ ...DEFAULT_BRUSH_SETTINGS,
+ size: 20,
+ hardness: 100,
+ opacity: 1,
+ flow: 1,
+ spacing: 25,
+ tip: 'round',
+ },
+ },
+ {
+ id: 'soft-round-pressure',
+ name: 'Soft Round Pressure',
+ category: 'soft',
+ settings: {
+ ...DEFAULT_BRUSH_SETTINGS,
+ size: 30,
+ hardness: 0,
+ opacity: 1,
+ flow: 1,
+ spacing: 25,
+ tip: 'round',
+ sizeDynamics: {
+ control: 'pen-pressure',
+ minValue: 0.1,
+ jitter: 0,
+ },
+ opacityDynamics: {
+ control: 'pen-pressure',
+ minValue: 0.2,
+ jitter: 0,
+ },
+ },
+ },
+ {
+ id: 'hard-round-pressure',
+ name: 'Hard Round Pressure',
+ category: 'hard',
+ settings: {
+ ...DEFAULT_BRUSH_SETTINGS,
+ size: 20,
+ hardness: 100,
+ opacity: 1,
+ flow: 1,
+ spacing: 25,
+ tip: 'round',
+ sizeDynamics: {
+ control: 'pen-pressure',
+ minValue: 0.1,
+ jitter: 0,
+ },
+ },
+ },
+ {
+ id: 'airbrush-soft',
+ name: 'Airbrush Soft',
+ category: 'soft',
+ settings: {
+ ...DEFAULT_BRUSH_SETTINGS,
+ size: 100,
+ hardness: 0,
+ opacity: 0.3,
+ flow: 0.5,
+ spacing: 10,
+ tip: 'round',
+ buildUp: true,
+ },
+ },
+ {
+ id: 'chalk',
+ name: 'Chalk',
+ category: 'texture',
+ settings: {
+ ...DEFAULT_BRUSH_SETTINGS,
+ size: 40,
+ hardness: 80,
+ opacity: 0.8,
+ flow: 0.6,
+ spacing: 20,
+ tip: 'round',
+ sizeDynamics: {
+ control: 'pen-pressure',
+ minValue: 0.5,
+ jitter: 0.1,
+ },
+ opacityDynamics: {
+ control: 'pen-pressure',
+ minValue: 0.3,
+ jitter: 0.15,
+ },
+ },
+ },
+ {
+ id: 'charcoal',
+ name: 'Charcoal',
+ category: 'artistic',
+ settings: {
+ ...DEFAULT_BRUSH_SETTINGS,
+ size: 30,
+ hardness: 50,
+ opacity: 0.7,
+ flow: 0.8,
+ spacing: 15,
+ tip: 'round',
+ roundness: 60,
+ angle: 45,
+ sizeDynamics: {
+ control: 'pen-pressure',
+ minValue: 0.3,
+ jitter: 0.05,
+ },
+ opacityDynamics: {
+ control: 'pen-pressure',
+ minValue: 0.2,
+ jitter: 0.1,
+ },
+ },
+ },
+ {
+ id: 'pencil-hard',
+ name: 'Pencil Hard',
+ category: 'hard',
+ settings: {
+ ...DEFAULT_BRUSH_SETTINGS,
+ size: 4,
+ hardness: 100,
+ opacity: 1,
+ flow: 1,
+ spacing: 10,
+ tip: 'round',
+ sizeDynamics: {
+ control: 'pen-pressure',
+ minValue: 0.5,
+ jitter: 0,
+ },
+ },
+ },
+ {
+ id: 'pencil-soft',
+ name: 'Pencil Soft',
+ category: 'soft',
+ settings: {
+ ...DEFAULT_BRUSH_SETTINGS,
+ size: 6,
+ hardness: 70,
+ opacity: 0.8,
+ flow: 1,
+ spacing: 10,
+ tip: 'round',
+ sizeDynamics: {
+ control: 'pen-pressure',
+ minValue: 0.3,
+ jitter: 0,
+ },
+ opacityDynamics: {
+ control: 'pen-pressure',
+ minValue: 0.4,
+ jitter: 0,
+ },
+ },
+ },
+ {
+ id: 'marker',
+ name: 'Marker',
+ category: 'hard',
+ settings: {
+ ...DEFAULT_BRUSH_SETTINGS,
+ size: 15,
+ hardness: 100,
+ opacity: 0.8,
+ flow: 1,
+ spacing: 15,
+ tip: 'round',
+ roundness: 70,
+ angle: -30,
+ },
+ },
+ {
+ id: 'watercolor-wet',
+ name: 'Watercolor Wet',
+ category: 'artistic',
+ settings: {
+ ...DEFAULT_BRUSH_SETTINGS,
+ size: 60,
+ hardness: 0,
+ opacity: 0.4,
+ flow: 0.3,
+ spacing: 15,
+ tip: 'round',
+ buildUp: true,
+ sizeDynamics: {
+ control: 'pen-pressure',
+ minValue: 0.5,
+ jitter: 0.1,
+ },
+ opacityDynamics: {
+ control: 'pen-pressure',
+ minValue: 0.1,
+ jitter: 0.2,
+ },
+ },
+ },
+ {
+ id: 'ink-pen',
+ name: 'Ink Pen',
+ category: 'hard',
+ settings: {
+ ...DEFAULT_BRUSH_SETTINGS,
+ size: 3,
+ hardness: 100,
+ opacity: 1,
+ flow: 1,
+ spacing: 5,
+ tip: 'round',
+ smoothing: 70,
+ sizeDynamics: {
+ control: 'pen-pressure',
+ minValue: 0.2,
+ jitter: 0,
+ },
+ },
+ },
+ {
+ id: 'flat-brush',
+ name: 'Flat Brush',
+ category: 'artistic',
+ settings: {
+ ...DEFAULT_BRUSH_SETTINGS,
+ size: 40,
+ hardness: 90,
+ opacity: 1,
+ flow: 1,
+ spacing: 20,
+ tip: 'square',
+ roundness: 30,
+ angle: 0,
+ sizeDynamics: {
+ control: 'pen-pressure',
+ minValue: 0.5,
+ jitter: 0,
+ },
+ },
+ },
+ {
+ id: 'scatter-brush',
+ name: 'Scatter Brush',
+ category: 'special',
+ settings: {
+ ...DEFAULT_BRUSH_SETTINGS,
+ size: 25,
+ hardness: 100,
+ opacity: 1,
+ flow: 1,
+ spacing: 80,
+ tip: 'round',
+ sizeDynamics: {
+ control: 'off',
+ minValue: 0.3,
+ jitter: 0.5,
+ },
+ opacityDynamics: {
+ control: 'off',
+ minValue: 0.5,
+ jitter: 0.3,
+ },
+ },
+ },
+ {
+ id: 'eraser-soft',
+ name: 'Soft Eraser',
+ category: 'general',
+ settings: {
+ ...DEFAULT_BRUSH_SETTINGS,
+ size: 50,
+ hardness: 0,
+ opacity: 1,
+ flow: 1,
+ spacing: 25,
+ tip: 'round',
+ },
+ },
+ {
+ id: 'eraser-hard',
+ name: 'Hard Eraser',
+ category: 'general',
+ settings: {
+ ...DEFAULT_BRUSH_SETTINGS,
+ size: 30,
+ hardness: 100,
+ opacity: 1,
+ flow: 1,
+ spacing: 25,
+ tip: 'round',
+ },
+ },
+ {
+ id: 'smudge-soft',
+ name: 'Smudge Soft',
+ category: 'special',
+ settings: {
+ ...DEFAULT_BRUSH_SETTINGS,
+ size: 40,
+ hardness: 0,
+ opacity: 0.5,
+ flow: 1,
+ spacing: 10,
+ tip: 'round',
+ sizeDynamics: {
+ control: 'pen-pressure',
+ minValue: 0.5,
+ jitter: 0,
+ },
+ },
+ },
+ {
+ id: 'blur-brush',
+ name: 'Blur Brush',
+ category: 'special',
+ settings: {
+ ...DEFAULT_BRUSH_SETTINGS,
+ size: 50,
+ hardness: 0,
+ opacity: 0.5,
+ flow: 1,
+ spacing: 15,
+ tip: 'round',
+ },
+ },
+];
+
+export class BrushPresetManager {
+ private presets: Map<string, BrushPreset> = new Map();
+ private customPresets: Map<string, BrushPreset> = new Map();
+
+ constructor() {
+ BRUSH_PRESETS.forEach((preset) => {
+ this.presets.set(preset.id, preset);
+ });
+ }
+
+ getPreset(id: string): BrushPreset | undefined {
+ return this.presets.get(id) || this.customPresets.get(id);
+ }
+
+ getAllPresets(): BrushPreset[] {
+ return [...this.presets.values(), ...this.customPresets.values()];
+ }
+
+ getPresetsByCategory(category: BrushCategory): BrushPreset[] {
+ return this.getAllPresets().filter((preset) => preset.category === category);
+ }
+
+ addCustomPreset(name: string, settings: BrushSettings): BrushPreset {
+ const id = `custom-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
+ const preset: BrushPreset = {
+ id,
+ name,
+ category: 'custom',
+ settings: { ...settings },
+ };
+ this.customPresets.set(id, preset);
+ return preset;
+ }
+
+ updateCustomPreset(id: string, updates: Partial<Omit<BrushPreset, 'id'>>): boolean {
+ const preset = this.customPresets.get(id);
+ if (!preset) return false;
+
+ this.customPresets.set(id, {
+ ...preset,
+ ...updates,
+ settings: updates.settings ? { ...updates.settings } : preset.settings,
+ });
+ return true;
+ }
+
+ deleteCustomPreset(id: string): boolean {
+ return this.customPresets.delete(id);
+ }
+
+ getCustomPresets(): BrushPreset[] {
+ return [...this.customPresets.values()];
+ }
+
+ exportCustomPresets(): string {
+ return JSON.stringify([...this.customPresets.values()]);
+ }
+
+ importCustomPresets(json: string): number {
+ try {
+ const presets: BrushPreset[] = JSON.parse(json);
+ let imported = 0;
+ presets.forEach((preset) => {
+ if (preset.id && preset.name && preset.settings) {
+ this.customPresets.set(preset.id, preset);
+ imported++;
+ }
+ });
+ return imported;
+ } catch {
+ return 0;
+ }
+ }
+
+ searchPresets(query: string): BrushPreset[] {
+ const lowerQuery = query.toLowerCase();
+ return this.getAllPresets().filter(
+ (preset) =>
+ preset.name.toLowerCase().includes(lowerQuery) ||
+ preset.category.toLowerCase().includes(lowerQuery)
+ );
+ }
+}
+
+export const brushPresetManager = new BrushPresetManager();
diff --git a/apps/image/src/tools/paint/eraser.ts b/apps/image/src/tools/paint/eraser.ts
new file mode 100644
index 00000000..6eb85026
--- /dev/null
+++ b/apps/image/src/tools/paint/eraser.ts
@@ -0,0 +1,278 @@
+import { BrushSettings, DEFAULT_BRUSH_SETTINGS, BrushEngine } from '../brush/brush-engine';
+
+export type EraserMode = 'brush' | 'pencil' | 'block';
+
+export interface EraserSettings extends BrushSettings {
+ mode: EraserMode;
+ eraseToHistory: boolean;
+ historyStateIndex: number | null;
+}
+
+export const DEFAULT_ERASER_SETTINGS: EraserSettings = {
+ ...DEFAULT_BRUSH_SETTINGS,
+ hardness: 100,
+ mode: 'brush',
+ eraseToHistory: false,
+ historyStateIndex: null,
+};
+
+export interface EraserStroke {
+ points: Array<{
+ x: number;
+ y: number;
+ pressure: number;
+ }>;
+ settings: EraserSettings;
+}
+
+export class EraserTool {
+ private settings: EraserSettings;
+ private brushEngine: BrushEngine;
+ private isErasing: boolean = false;
+ private currentStroke: EraserStroke | null = null;
+ private historyCanvas: OffscreenCanvas | null = null;
+
+ constructor(settings: Partial<EraserSettings> = {}) {
+ this.settings = { ...DEFAULT_ERASER_SETTINGS, ...settings };
+ this.brushEngine = new BrushEngine(1920, 1080);
+ }
+
+ resize(width: number, height: number): void {
+ this.brushEngine.resize(width, height);
+ }
+
+ setHistoryCanvas(canvas: OffscreenCanvas): void {
+ this.historyCanvas = canvas;
+ }
+
+ startErase(x: number, y: number, pressure: number = 1): void {
+ this.isErasing = true;
+ this.currentStroke = {
+ points: [{ x, y, pressure }],
+ settings: { ...this.settings },
+ };
+ }
+
+ continueErase(x: number, y: number, pressure: number = 1): void {
+ if (!this.isErasing || !this.currentStroke) return;
+ this.currentStroke.points.push({ x, y, pressure });
+ }
+
+ endErase(): EraserStroke | null {
+ this.isErasing = false;
+ const stroke = this.currentStroke;
+ this.currentStroke = null;
+ return stroke;
+ }
+
+ applyErase(
+ ctx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D,
+ stroke: EraserStroke
+ ): void {
+ const { points, settings } = stroke;
+ if (points.length < 1) return;
+
+ ctx.save();
+
+ if (settings.eraseToHistory && this.historyCanvas) {
+ this.eraseToHistoryState(ctx, stroke);
+ } else {
+ ctx.globalCompositeOperation = 'destination-out';
+
+ const spacingPx = Math.max(1, (settings.size * settings.spacing) / 100);
+
+ for (let i = 0; i < points.length; i++) {
+ const point = points[i];
+
+ if (i > 0) {
+ const prev = points[i - 1];
+ const dx = point.x - prev.x;
+ const dy = point.y - prev.y;
+ const distance = Math.sqrt(dx * dx + dy * dy);
+ const steps = Math.ceil(distance / spacingPx);
+
+ for (let step = 0; step < steps; step++) {
+ const t = step / steps;
+ const x = prev.x + dx * t;
+ const y = prev.y + dy * t;
+ const pressure = prev.pressure + (point.pressure - prev.pressure) * t;
+
+ this.drawEraserDab(ctx, x, y, settings, pressure);
+ }
+ }
+
+ this.drawEraserDab(ctx, point.x, point.y, settings, point.pressure);
+ }
+ }
+
+ ctx.restore();
+ }
+
+ private drawEraserDab(
+ ctx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D,
+ x: number,
+ y: number,
+ settings: EraserSettings,
+ pressure: number
+ ): void {
+ const size = settings.size * (settings.sizeDynamics.control === 'pen-pressure'
+ ? settings.sizeDynamics.minValue + (1 - settings.sizeDynamics.minValue) * pressure
+ : 1);
+ const opacity = settings.opacity * settings.flow * (settings.opacityDynamics.control === 'pen-pressure'
+ ? settings.opacityDynamics.minValue + (1 - settings.opacityDynamics.minValue) * pressure
+ : 1);
+
+ ctx.save();
+ ctx.globalAlpha = opacity;
+
+ const halfSize = size / 2;
+
+ switch (settings.mode) {
+ case 'block':
+ ctx.fillStyle = 'white';
+ ctx.fillRect(x - halfSize, y - halfSize, size, size);
+ break;
+
+ case 'pencil':
+ ctx.fillStyle = 'white';
+ ctx.beginPath();
+ ctx.arc(x, y, halfSize, 0, Math.PI * 2);
+ ctx.fill();
+ break;
+
+ case 'brush':
+ default:
+ const hardness = settings.hardness / 100;
+ const gradient = ctx.createRadialGradient(x, y, 0, x, y, halfSize);
+
+ if (hardness >= 0.99) {
+ gradient.addColorStop(0, 'rgba(255, 255, 255, 1)');
+ gradient.addColorStop(1, 'rgba(255, 255, 255, 1)');
+ } else {
+ const hardnessPoint = Math.max(0.01, hardness);
+ gradient.addColorStop(0, 'rgba(255, 255, 255, 1)');
+ gradient.addColorStop(hardnessPoint, 'rgba(255, 255, 255, 1)');
+ gradient.addColorStop(1, 'rgba(255, 255, 255, 0)');
+ }
+
+ ctx.fillStyle = gradient;
+ ctx.beginPath();
+ ctx.arc(x, y, halfSize, 0, Math.PI * 2);
+ ctx.fill();
+ break;
+ }
+
+ ctx.restore();
+ }
+
+ private eraseToHistoryState(
+ ctx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D,
+ stroke: EraserStroke
+ ): void {
+ if (!this.historyCanvas) return;
+
+ const { points, settings } = stroke;
+ const historyCtx = this.historyCanvas.getContext('2d')!;
+
+ const spacingPx = Math.max(1, (settings.size * settings.spacing) / 100);
+
+ for (let i = 0; i < points.length; i++) {
+ const point = points[i];
+
+ if (i > 0) {
+ const prev = points[i - 1];
+ const dx = point.x - prev.x;
+ const dy = point.y - prev.y;
+ const distance = Math.sqrt(dx * dx + dy * dy);
+ const steps = Math.ceil(distance / spacingPx);
+
+ for (let step = 0; step < steps; step++) {
+ const t = step / steps;
+ const x = prev.x + dx * t;
+ const y = prev.y + dy * t;
+ const pressure = prev.pressure + (point.pressure - prev.pressure) * t;
+
+ this.restoreFromHistory(ctx, historyCtx, x, y, settings, pressure);
+ }
+ }
+
+ this.restoreFromHistory(ctx, historyCtx, point.x, point.y, settings, point.pressure);
+ }
+ }
+
+ private restoreFromHistory(
+ ctx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D,
+ historyCtx: OffscreenCanvasRenderingContext2D,
+ x: number,
+ y: number,
+ settings: EraserSettings,
+ pressure: number
+ ): void {
+ const size = Math.ceil(settings.size * (settings.sizeDynamics.control === 'pen-pressure'
+ ? settings.sizeDynamics.minValue + (1 - settings.sizeDynamics.minValue) * pressure
+ : 1));
+ const halfSize = size / 2;
+ const opacity = settings.opacity * settings.flow;
+
+ const historyData = historyCtx.getImageData(
+ Math.floor(x - halfSize),
+ Math.floor(y - halfSize),
+ size,
+ size
+ );
+
+ const tempCanvas = new OffscreenCanvas(size, size);
+ const tempCtx = tempCanvas.getContext('2d')!;
+ tempCtx.putImageData(historyData, 0, 0);
+
+ this.applyBrushMask(tempCtx, size, settings.hardness);
+
+ ctx.save();
+ ctx.globalAlpha = opacity;
+ ctx.drawImage(tempCanvas, x - halfSize, y - halfSize);
+ ctx.restore();
+ }
+
+ private applyBrushMask(ctx: OffscreenCanvasRenderingContext2D, size: number, hardness: number): void {
+ const imageData = ctx.getImageData(0, 0, size, size);
+ const data = imageData.data;
+ const center = size / 2;
+ const radius = size / 2;
+ const hardnessNorm = hardness / 100;
+
+ for (let y = 0; y < size; y++) {
+ for (let x = 0; x < size; x++) {
+ const dx = x - center;
+ const dy = y - center;
+ const distance = Math.sqrt(dx * dx + dy * dy);
+ const normalizedDist = distance / radius;
+
+ let alpha = 1;
+ if (normalizedDist > hardnessNorm) {
+ alpha = 1 - (normalizedDist - hardnessNorm) / (1 - hardnessNorm);
+ alpha = Math.max(0, Math.min(1, alpha));
+ }
+ if (normalizedDist > 1) {
+ alpha = 0;
+ }
+
+ const idx = (y * size + x) * 4;
+ data[idx + 3] = Math.round(data[idx + 3] * alpha);
+ }
+ }
+
+ ctx.putImageData(imageData, 0, 0);
+ }
+
+ getSettings(): EraserSettings {
+ return { ...this.settings };
+ }
+
+ updateSettings(settings: Partial<EraserSettings>): void {
+ this.settings = { ...this.settings, ...settings };
+ }
+
+ isActive(): boolean {
+ return this.isErasing;
+ }
+}
diff --git a/apps/image/src/tools/retouch/clone-stamp.ts b/apps/image/src/tools/retouch/clone-stamp.ts
new file mode 100644
index 00000000..171899bb
--- /dev/null
+++ b/apps/image/src/tools/retouch/clone-stamp.ts
@@ -0,0 +1,212 @@
+import { BrushSettings, DEFAULT_BRUSH_SETTINGS } from '../brush/brush-engine';
+
+export type SampleMode = 'current' | 'current-below' | 'all';
+export type BlendMode = 'normal' | 'multiply' | 'screen' | 'overlay' | 'darken' | 'lighten';
+
+export interface CloneStampSettings extends BrushSettings {
+ sourcePoint: { x: number; y: number } | null;
+ sourceLayerId: string | null;
+ aligned: boolean;
+ sampleMode: SampleMode;
+ blendMode: BlendMode;
+}
+
+export const DEFAULT_CLONE_STAMP_SETTINGS: CloneStampSettings = {
+ ...DEFAULT_BRUSH_SETTINGS,
+ sourcePoint: null,
+ sourceLayerId: null,
+ aligned: true,
+ sampleMode: 'current',
+ blendMode: 'normal',
+};
+
+export interface CloneStampState {
+ isCloning: boolean;
+ sourceSet: boolean;
+ initialSourcePoint: { x: number; y: number } | null;
+ initialTargetPoint: { x: number; y: number } | null;
+ offset: { x: number; y: number };
+}
+
+export class CloneStampTool {
+ private settings: CloneStampSettings;
+ private state: CloneStampState;
+ private sourceCanvas: OffscreenCanvas | null = null;
+ private sourceCtx: OffscreenCanvasRenderingContext2D | null = null;
+
+ constructor(settings: Partial<CloneStampSettings> = {}) {
+ this.settings = { ...DEFAULT_CLONE_STAMP_SETTINGS, ...settings };
+ this.state = {
+ isCloning: false,
+ sourceSet: false,
+ initialSourcePoint: null,
+ initialTargetPoint: null,
+ offset: { x: 0, y: 0 },
+ };
+ }
+
+ setSource(x: number, y: number, layerId: string | null = null): void {
+ this.settings.sourcePoint = { x, y };
+ this.settings.sourceLayerId = layerId;
+ this.state.sourceSet = true;
+ this.state.initialSourcePoint = { x, y };
+ this.state.initialTargetPoint = null;
+ this.state.offset = { x: 0, y: 0 };
+ }
+
+ clearSource(): void {
+ this.settings.sourcePoint = null;
+ this.settings.sourceLayerId = null;
+ this.state.sourceSet = false;
+ this.state.initialSourcePoint = null;
+ this.state.initialTargetPoint = null;
+ this.state.offset = { x: 0, y: 0 };
+ }
+
+ hasSource(): boolean {
+ return this.state.sourceSet && this.settings.sourcePoint !== null;
+ }
+
+ setSourceCanvas(canvas: OffscreenCanvas): void {
+ this.sourceCanvas = canvas;
+ this.sourceCtx = canvas.getContext('2d', { willReadFrequently: true });
+ }
+
+ startClone(targetX: number, targetY: number): void {
+ if (!this.hasSource()) return;
+
+ this.state.isCloning = true;
+
+ if (this.settings.aligned) {
+ if (!this.state.initialTargetPoint) {
+ this.state.initialTargetPoint = { x: targetX, y: targetY };
+ this.state.offset = {
+ x: this.settings.sourcePoint!.x - targetX,
+ y: this.settings.sourcePoint!.y - targetY,
+ };
+ }
+ } else {
+ this.state.offset = {
+ x: this.settings.sourcePoint!.x - targetX,
+ y: this.settings.sourcePoint!.y - targetY,
+ };
+ }
+ }
+
+ clone(
+ targetCtx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D,
+ targetX: number,
+ targetY: number
+ ): void {
+ if (!this.state.isCloning || !this.sourceCanvas || !this.sourceCtx) return;
+
+ const sourceX = targetX + this.state.offset.x;
+ const sourceY = targetY + this.state.offset.y;
+
+ const size = Math.ceil(this.settings.size);
+ const halfSize = size / 2;
+
+ if (
+ sourceX - halfSize < 0 ||
+ sourceY - halfSize < 0 ||
+ sourceX + halfSize > this.sourceCanvas.width ||
+ sourceY + halfSize > this.sourceCanvas.height
+ ) {
+ return;
+ }
+
+ const sourceData = this.sourceCtx.getImageData(
+ Math.floor(sourceX - halfSize),
+ Math.floor(sourceY - halfSize),
+ size,
+ size
+ );
+
+ const tempCanvas = new OffscreenCanvas(size, size);
+ const tempCtx = tempCanvas.getContext('2d')!;
+ tempCtx.putImageData(sourceData, 0, 0);
+
+ this.applyBrushMask(tempCtx, size, this.settings.hardness);
+
+ targetCtx.save();
+ targetCtx.globalAlpha = this.settings.opacity * this.settings.flow;
+ targetCtx.globalCompositeOperation = this.getCompositeOperation(this.settings.blendMode);
+ targetCtx.drawImage(tempCanvas, targetX - halfSize, targetY - halfSize);
+ targetCtx.restore();
+ }
+
+ endClone(): void {
+ this.state.isCloning = false;
+ }
+
+ private applyBrushMask(
+ ctx: OffscreenCanvasRenderingContext2D,
+ size: number,
+ hardness: number
+ ): void {
+ const imageData = ctx.getImageData(0, 0, size, size);
+ const data = imageData.data;
+ const center = size / 2;
+ const radius = size / 2;
+ const hardnessNorm = hardness / 100;
+
+ for (let y = 0; y < size; y++) {
+ for (let x = 0; x < size; x++) {
+ const dx = x - center;
+ const dy = y - center;
+ const distance = Math.sqrt(dx * dx + dy * dy);
+ const normalizedDist = distance / radius;
+
+ let alpha = 1;
+ if (normalizedDist > hardnessNorm) {
+ alpha = 1 - (normalizedDist - hardnessNorm) / (1 - hardnessNorm);
+ alpha = Math.max(0, Math.min(1, alpha));
+ }
+ if (normalizedDist > 1) {
+ alpha = 0;
+ }
+
+ const idx = (y * size + x) * 4;
+ data[idx + 3] = Math.round(data[idx + 3] * alpha);
+ }
+ }
+
+ ctx.putImageData(imageData, 0, 0);
+ }
+
+ private getCompositeOperation(blendMode: BlendMode): GlobalCompositeOperation {
+ const modeMap: Record<BlendMode, GlobalCompositeOperation> = {
+ normal: 'source-over',
+ multiply: 'multiply',
+ screen: 'screen',
+ overlay: 'overlay',
+ darken: 'darken',
+ lighten: 'lighten',
+ };
+ return modeMap[blendMode] || 'source-over';
+ }
+
+ getSettings(): CloneStampSettings {
+ return { ...this.settings };
+ }
+
+ updateSettings(settings: Partial<CloneStampSettings>): void {
+ this.settings = { ...this.settings, ...settings };
+ }
+
+ getSourcePoint(): { x: number; y: number } | null {
+ return this.settings.sourcePoint;
+ }
+
+ getOffset(): { x: number; y: number } {
+ return { ...this.state.offset };
+ }
+
+ getCurrentSourcePosition(targetX: number, targetY: number): { x: number; y: number } | null {
+ if (!this.hasSource()) return null;
+ return {
+ x: targetX + this.state.offset.x,
+ y: targetY + this.state.offset.y,
+ };
+ }
+}
diff --git a/apps/image/src/tools/retouch/dodge-burn.ts b/apps/image/src/tools/retouch/dodge-burn.ts
new file mode 100644
index 00000000..220496f0
--- /dev/null
+++ b/apps/image/src/tools/retouch/dodge-burn.ts
@@ -0,0 +1,271 @@
+import { BrushSettings, DEFAULT_BRUSH_SETTINGS } from '../brush/brush-engine';
+
+export type DodgeBurnType = 'dodge' | 'burn';
+export type ToneRange = 'shadows' | 'midtones' | 'highlights';
+
+export interface DodgeBurnSettings extends BrushSettings {
+ type: DodgeBurnType;
+ range: ToneRange;
+ exposure: number;
+ protectTones: boolean;
+}
+
+export const DEFAULT_DODGE_BURN_SETTINGS: DodgeBurnSettings = {
+ ...DEFAULT_BRUSH_SETTINGS,
+ type: 'dodge',
+ range: 'midtones',
+ exposure: 50,
+ protectTones: true,
+};
+
+export interface DodgeBurnStroke {
+ points: Array<{
+ x: number;
+ y: number;
+ pressure: number;
+ }>;
+ settings: DodgeBurnSettings;
+}
+
+export class DodgeBurnTool {
+ private settings: DodgeBurnSettings;
+ private canvas: OffscreenCanvas | null = null;
+ private ctx: OffscreenCanvasRenderingContext2D | null = null;
+ private isActive: boolean = false;
+ private currentStroke: DodgeBurnStroke | null = null;
+
+ constructor(settings: Partial<DodgeBurnSettings> = {}) {
+ this.settings = { ...DEFAULT_DODGE_BURN_SETTINGS, ...settings };
+ }
+
+ setCanvas(canvas: OffscreenCanvas): void {
+ this.canvas = canvas;
+ this.ctx = canvas.getContext('2d', { willReadFrequently: true });
+ }
+
+ startStroke(x: number, y: number, pressure: number = 1): void {
+ this.isActive = true;
+ this.currentStroke = {
+ points: [{ x, y, pressure }],
+ settings: { ...this.settings },
+ };
+ }
+
+ continueStroke(x: number, y: number, pressure: number = 1): void {
+ if (!this.isActive || !this.currentStroke) return;
+ this.currentStroke.points.push({ x, y, pressure });
+ }
+
+ endStroke(): DodgeBurnStroke | null {
+ this.isActive = false;
+ const stroke = this.currentStroke;
+ this.currentStroke = null;
+ return stroke;
+ }
+
+ apply(
+ outputCtx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D,
+ x: number,
+ y: number,
+ pressure: number = 1
+ ): void {
+ if (!this.canvas || !this.ctx) return;
+
+ const size = Math.ceil(this.settings.size);
+ const halfSize = size / 2;
+
+ const targetX = Math.floor(x - halfSize);
+ const targetY = Math.floor(y - halfSize);
+
+ if (
+ targetX < 0 ||
+ targetY < 0 ||
+ targetX + size > this.canvas.width ||
+ targetY + size > this.canvas.height
+ ) {
+ return;
+ }
+
+ const imageData = this.ctx.getImageData(targetX, targetY, size, size);
+ const adjustedData = this.adjustTones(imageData, pressure);
+
+ const tempCanvas = new OffscreenCanvas(size, size);
+ const tempCtx = tempCanvas.getContext('2d')!;
+ tempCtx.putImageData(adjustedData, 0, 0);
+
+ this.applyBrushMask(tempCtx, size, this.settings.hardness);
+
+ outputCtx.save();
+ outputCtx.globalAlpha = this.settings.opacity * this.settings.flow;
+ outputCtx.drawImage(tempCanvas, targetX, targetY);
+ outputCtx.restore();
+ }
+
+ applyStroke(
+ outputCtx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D,
+ stroke: DodgeBurnStroke
+ ): void {
+ const { points, settings } = stroke;
+ if (points.length < 1) return;
+
+ const originalSettings = { ...this.settings };
+ this.settings = { ...settings };
+
+ const spacingPx = Math.max(1, (settings.size * settings.spacing) / 100);
+
+ for (let i = 0; i < points.length; i++) {
+ const point = points[i];
+
+ if (i > 0) {
+ const prev = points[i - 1];
+ const dx = point.x - prev.x;
+ const dy = point.y - prev.y;
+ const distance = Math.sqrt(dx * dx + dy * dy);
+ const steps = Math.ceil(distance / spacingPx);
+
+ for (let step = 0; step < steps; step++) {
+ const t = step / steps;
+ const interpX = prev.x + dx * t;
+ const interpY = prev.y + dy * t;
+ const interpPressure = prev.pressure + (point.pressure - prev.pressure) * t;
+
+ this.apply(outputCtx, interpX, interpY, interpPressure);
+ }
+ }
+
+ this.apply(outputCtx, point.x, point.y, point.pressure);
+ }
+
+ this.settings = originalSettings;
+ }
+
+ private adjustTones(imageData: ImageData, pressure: number): ImageData {
+ const data = imageData.data;
+ const exposure = (this.settings.exposure / 100) * pressure;
+ const isDodge = this.settings.type === 'dodge';
+
+ for (let i = 0; i < data.length; i += 4) {
+ const r = data[i];
+ const g = data[i + 1];
+ const b = data[i + 2];
+
+ const luminance = (r * 0.299 + g * 0.587 + b * 0.114) / 255;
+ const rangeWeight = this.getRangeWeight(luminance);
+
+ if (rangeWeight <= 0) continue;
+
+ const effectStrength = exposure * rangeWeight;
+
+ let newR: number, newG: number, newB: number;
+
+ if (isDodge) {
+ if (this.settings.protectTones) {
+ newR = this.dodgeWithProtection(r, effectStrength);
+ newG = this.dodgeWithProtection(g, effectStrength);
+ newB = this.dodgeWithProtection(b, effectStrength);
+ } else {
+ newR = Math.min(255, r + (255 - r) * effectStrength);
+ newG = Math.min(255, g + (255 - g) * effectStrength);
+ newB = Math.min(255, b + (255 - b) * effectStrength);
+ }
+ } else {
+ if (this.settings.protectTones) {
+ newR = this.burnWithProtection(r, effectStrength);
+ newG = this.burnWithProtection(g, effectStrength);
+ newB = this.burnWithProtection(b, effectStrength);
+ } else {
+ newR = Math.max(0, r * (1 - effectStrength));
+ newG = Math.max(0, g * (1 - effectStrength));
+ newB = Math.max(0, b * (1 - effectStrength));
+ }
+ }
+
+ data[i] = Math.round(newR);
+ data[i + 1] = Math.round(newG);
+ data[i + 2] = Math.round(newB);
+ }
+
+ return imageData;
+ }
+
+ private getRangeWeight(luminance: number): number {
+ switch (this.settings.range) {
+ case 'shadows':
+ if (luminance <= 0.25) return 1;
+ if (luminance <= 0.5) return 1 - (luminance - 0.25) / 0.25;
+ return 0;
+
+ case 'highlights':
+ if (luminance >= 0.75) return 1;
+ if (luminance >= 0.5) return (luminance - 0.5) / 0.25;
+ return 0;
+
+ case 'midtones':
+ default:
+ if (luminance >= 0.25 && luminance <= 0.75) {
+ const distFromCenter = Math.abs(luminance - 0.5);
+ return 1 - distFromCenter / 0.25;
+ }
+ return 0;
+ }
+ }
+
+ private dodgeWithProtection(value: number, strength: number): number {
+ const normalized = value / 255;
+ const dodged = normalized + (1 - normalized) * strength * 0.5;
+ const saturationPreserve = 1 - strength * 0.3;
+ const protected_ = normalized + (dodged - normalized) * saturationPreserve;
+ return Math.min(255, protected_ * 255);
+ }
+
+ private burnWithProtection(value: number, strength: number): number {
+ const normalized = value / 255;
+ const burned = normalized * (1 - strength * 0.5);
+ const saturationPreserve = 1 - strength * 0.3;
+ const protected_ = normalized + (burned - normalized) * saturationPreserve;
+ return Math.max(0, protected_ * 255);
+ }
+
+ private applyBrushMask(ctx: OffscreenCanvasRenderingContext2D, size: number, hardness: number): void {
+ const imageData = ctx.getImageData(0, 0, size, size);
+ const data = imageData.data;
+ const center = size / 2;
+ const radius = size / 2;
+ const hardnessNorm = hardness / 100;
+
+ for (let y = 0; y < size; y++) {
+ for (let x = 0; x < size; x++) {
+ const dx = x - center;
+ const dy = y - center;
+ const distance = Math.sqrt(dx * dx + dy * dy);
+ const normalizedDist = distance / radius;
+
+ let alpha = 1;
+ if (normalizedDist > hardnessNorm) {
+ alpha = 1 - (normalizedDist - hardnessNorm) / (1 - hardnessNorm);
+ alpha = Math.max(0, Math.min(1, alpha));
+ }
+ if (normalizedDist > 1) {
+ alpha = 0;
+ }
+
+ const idx = (y * size + x) * 4;
+ data[idx + 3] = Math.round(data[idx + 3] * alpha);
+ }
+ }
+
+ ctx.putImageData(imageData, 0, 0);
+ }
+
+ getSettings(): DodgeBurnSettings {
+ return { ...this.settings };
+ }
+
+ updateSettings(settings: Partial<DodgeBurnSettings>): void {
+ this.settings = { ...this.settings, ...settings };
+ }
+
+ isActiveStroke(): boolean {
+ return this.isActive;
+ }
+}
diff --git a/apps/image/src/tools/retouch/healing-brush.ts b/apps/image/src/tools/retouch/healing-brush.ts
new file mode 100644
index 00000000..afb8454a
--- /dev/null
+++ b/apps/image/src/tools/retouch/healing-brush.ts
@@ -0,0 +1,248 @@
+import { CloneStampSettings, DEFAULT_CLONE_STAMP_SETTINGS } from './clone-stamp';
+
+export type HealingMode = 'normal' | 'replace' | 'multiply' | 'screen' | 'darken' | 'lighten';
+
+export interface HealingBrushSettings extends Omit<CloneStampSettings, 'blendMode'> {
+ healingMode: HealingMode;
+ diffusion: number;
+}
+
+export const DEFAULT_HEALING_BRUSH_SETTINGS: HealingBrushSettings = {
+ ...DEFAULT_CLONE_STAMP_SETTINGS,
+ healingMode: 'normal',
+ diffusion: 50,
+};
+
+export class HealingBrushTool {
+ private settings: HealingBrushSettings;
+ private sourceCanvas: OffscreenCanvas | null = null;
+ private sourceCtx: OffscreenCanvasRenderingContext2D | null = null;
+ private targetCtx: OffscreenCanvasRenderingContext2D | null = null;
+ private isHealing: boolean = false;
+ private offset: { x: number; y: number } = { x: 0, y: 0 };
+ private initialTargetPoint: { x: number; y: number } | null = null;
+
+ constructor(settings: Partial<HealingBrushSettings> = {}) {
+ this.settings = { ...DEFAULT_HEALING_BRUSH_SETTINGS, ...settings };
+ }
+
+ setSource(x: number, y: number, _layerId: string | null = null): void {
+ this.settings.sourcePoint = { x, y };
+ this.initialTargetPoint = null;
+ this.offset = { x: 0, y: 0 };
+ }
+
+ clearSource(): void {
+ this.settings.sourcePoint = null;
+ this.initialTargetPoint = null;
+ this.offset = { x: 0, y: 0 };
+ }
+
+ hasSource(): boolean {
+ return this.settings.sourcePoint !== null;
+ }
+
+ setCanvases(source: OffscreenCanvas, target: OffscreenCanvas): void {
+ this.sourceCanvas = source;
+ this.sourceCtx = source.getContext('2d', { willReadFrequently: true });
+ this.targetCtx = target.getContext('2d', { willReadFrequently: true });
+ }
+
+ startHeal(targetX: number, targetY: number): void {
+ if (!this.hasSource()) return;
+
+ this.isHealing = true;
+
+ if (this.settings.aligned) {
+ if (!this.initialTargetPoint) {
+ this.initialTargetPoint = { x: targetX, y: targetY };
+ this.offset = {
+ x: this.settings.sourcePoint!.x - targetX,
+ y: this.settings.sourcePoint!.y - targetY,
+ };
+ }
+ } else {
+ this.offset = {
+ x: this.settings.sourcePoint!.x - targetX,
+ y: this.settings.sourcePoint!.y - targetY,
+ };
+ }
+ }
+
+ heal(
+ outputCtx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D,
+ targetX: number,
+ targetY: number
+ ): void {
+ if (!this.isHealing || !this.sourceCanvas || !this.sourceCtx || !this.targetCtx) return;
+
+ const sourceX = targetX + this.offset.x;
+ const sourceY = targetY + this.offset.y;
+
+ const size = Math.ceil(this.settings.size);
+ const halfSize = size / 2;
+
+ if (
+ sourceX - halfSize < 0 ||
+ sourceY - halfSize < 0 ||
+ sourceX + halfSize > this.sourceCanvas.width ||
+ sourceY + halfSize > this.sourceCanvas.height
+ ) {
+ return;
+ }
+
+ const sourceData = this.sourceCtx.getImageData(
+ Math.floor(sourceX - halfSize),
+ Math.floor(sourceY - halfSize),
+ size,
+ size
+ );
+
+ const targetData = this.targetCtx.getImageData(
+ Math.floor(targetX - halfSize),
+ Math.floor(targetY - halfSize),
+ size,
+ size
+ );
+
+ const healedData = this.blendTextures(sourceData, targetData, size);
+
+ const tempCanvas = new OffscreenCanvas(size, size);
+ const tempCtx = tempCanvas.getContext('2d')!;
+ tempCtx.putImageData(healedData, 0, 0);
+
+ this.applyBrushMask(tempCtx, size, this.settings.hardness);
+
+ outputCtx.save();
+ outputCtx.globalAlpha = this.settings.opacity * this.settings.flow;
+ outputCtx.drawImage(tempCanvas, targetX - halfSize, targetY - halfSize);
+ outputCtx.restore();
+ }
+
+ endHeal(): void {
+ this.isHealing = false;
+ }
+
+ private blendTextures(source: ImageData, target: ImageData, size: number): ImageData {
+ const result = new ImageData(size, size);
+ const srcData = source.data;
+ const tgtData = target.data;
+ const outData = result.data;
+
+ const srcAvg = this.calculateRegionAverage(srcData, size);
+ const tgtAvg = this.calculateRegionAverage(tgtData, size);
+
+ const diffusion = this.settings.diffusion / 100;
+ const center = size / 2;
+ const radius = size / 2;
+ const hardness = this.settings.hardness / 100;
+
+ for (let y = 0; y < size; y++) {
+ for (let x = 0; x < size; x++) {
+ const idx = (y * size + x) * 4;
+
+ const dx = x - center;
+ const dy = y - center;
+ const distance = Math.sqrt(dx * dx + dy * dy);
+ const normalizedDist = distance / radius;
+
+ let blendFactor = 1;
+ if (normalizedDist > hardness) {
+ blendFactor = 1 - (normalizedDist - hardness) / (1 - hardness);
+ blendFactor = Math.max(0, Math.min(1, blendFactor));
+ }
+ if (normalizedDist > 1) {
+ blendFactor = 0;
+ }
+
+ for (let c = 0; c < 3; c++) {
+ const srcVal = srcData[idx + c];
+ const tgtVal = tgtData[idx + c];
+
+ const srcNormalized = srcVal - srcAvg[c];
+ const tgtColor = tgtAvg[c];
+ const healedVal = srcNormalized + tgtColor;
+
+ const finalVal = tgtVal * (1 - blendFactor * diffusion) + healedVal * blendFactor * diffusion;
+
+ outData[idx + c] = Math.max(0, Math.min(255, Math.round(finalVal)));
+ }
+
+ outData[idx + 3] = Math.round(
+ tgtData[idx + 3] * (1 - blendFactor) + srcData[idx + 3] * blendFactor
+ );
+ }
+ }
+
+ return result;
+ }
+
+ private calculateRegionAverage(data: Uint8ClampedArray, _size: number): [number, number, number] {
+ let r = 0, g = 0, b = 0;
+ let count = 0;
+
+ for (let i = 0; i < data.length; i += 4) {
+ if (data[i + 3] > 0) {
+ r += data[i];
+ g += data[i + 1];
+ b += data[i + 2];
+ count++;
+ }
+ }
+
+ if (count === 0) return [128, 128, 128];
+
+ return [r / count, g / count, b / count];
+ }
+
+ private applyBrushMask(ctx: OffscreenCanvasRenderingContext2D, size: number, hardness: number): void {
+ const imageData = ctx.getImageData(0, 0, size, size);
+ const data = imageData.data;
+ const center = size / 2;
+ const radius = size / 2;
+ const hardnessNorm = hardness / 100;
+
+ for (let y = 0; y < size; y++) {
+ for (let x = 0; x < size; x++) {
+ const dx = x - center;
+ const dy = y - center;
+ const distance = Math.sqrt(dx * dx + dy * dy);
+ const normalizedDist = distance / radius;
+
+ let alpha = 1;
+ if (normalizedDist > hardnessNorm) {
+ alpha = 1 - (normalizedDist - hardnessNorm) / (1 - hardnessNorm);
+ alpha = Math.max(0, Math.min(1, alpha));
+ }
+ if (normalizedDist > 1) {
+ alpha = 0;
+ }
+
+ const idx = (y * size + x) * 4;
+ data[idx + 3] = Math.round(data[idx + 3] * alpha);
+ }
+ }
+
+ ctx.putImageData(imageData, 0, 0);
+ }
+
+ getSettings(): HealingBrushSettings {
+ return { ...this.settings };
+ }
+
+ updateSettings(settings: Partial<HealingBrushSettings>): void {
+ this.settings = { ...this.settings, ...settings };
+ }
+
+ getSourcePoint(): { x: number; y: number } | null {
+ return this.settings.sourcePoint;
+ }
+
+ getCurrentSourcePosition(targetX: number, targetY: number): { x: number; y: number } | null {
+ if (!this.hasSource()) return null;
+ return {
+ x: targetX + this.offset.x,
+ y: targetY + this.offset.y,
+ };
+ }
+}
diff --git a/apps/image/src/tools/retouch/sponge.ts b/apps/image/src/tools/retouch/sponge.ts
new file mode 100644
index 00000000..ad5deeff
--- /dev/null
+++ b/apps/image/src/tools/retouch/sponge.ts
@@ -0,0 +1,277 @@
+import { BrushSettings, DEFAULT_BRUSH_SETTINGS } from '../brush/brush-engine';
+
+export type SpongeMode = 'saturate' | 'desaturate';
+
+export interface SpongeSettings extends BrushSettings {
+ mode: SpongeMode;
+ flow: number;
+ vibrance: boolean;
+}
+
+export const DEFAULT_SPONGE_SETTINGS: SpongeSettings = {
+ ...DEFAULT_BRUSH_SETTINGS,
+ mode: 'desaturate',
+ flow: 0.5,
+ vibrance: true,
+};
+
+export interface SpongeStroke {
+ points: Array<{
+ x: number;
+ y: number;
+ pressure: number;
+ }>;
+ settings: SpongeSettings;
+}
+
+export class SpongeTool {
+ private settings: SpongeSettings;
+ private canvas: OffscreenCanvas | null = null;
+ private ctx: OffscreenCanvasRenderingContext2D | null = null;
+ private isActive: boolean = false;
+ private currentStroke: SpongeStroke | null = null;
+
+ constructor(settings: Partial<SpongeSettings> = {}) {
+ this.settings = { ...DEFAULT_SPONGE_SETTINGS, ...settings };
+ }
+
+ setCanvas(canvas: OffscreenCanvas): void {
+ this.canvas = canvas;
+ this.ctx = canvas.getContext('2d', { willReadFrequently: true });
+ }
+
+ startStroke(x: number, y: number, pressure: number = 1): void {
+ this.isActive = true;
+ this.currentStroke = {
+ points: [{ x, y, pressure }],
+ settings: { ...this.settings },
+ };
+ }
+
+ continueStroke(x: number, y: number, pressure: number = 1): void {
+ if (!this.isActive || !this.currentStroke) return;
+ this.currentStroke.points.push({ x, y, pressure });
+ }
+
+ endStroke(): SpongeStroke | null {
+ this.isActive = false;
+ const stroke = this.currentStroke;
+ this.currentStroke = null;
+ return stroke;
+ }
+
+ apply(
+ outputCtx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D,
+ x: number,
+ y: number,
+ pressure: number = 1
+ ): void {
+ if (!this.canvas || !this.ctx) return;
+
+ const size = Math.ceil(this.settings.size);
+ const halfSize = size / 2;
+
+ const targetX = Math.floor(x - halfSize);
+ const targetY = Math.floor(y - halfSize);
+
+ if (
+ targetX < 0 ||
+ targetY < 0 ||
+ targetX + size > this.canvas.width ||
+ targetY + size > this.canvas.height
+ ) {
+ return;
+ }
+
+ const imageData = this.ctx.getImageData(targetX, targetY, size, size);
+ const adjustedData = this.adjustSaturation(imageData, pressure);
+
+ const tempCanvas = new OffscreenCanvas(size, size);
+ const tempCtx = tempCanvas.getContext('2d')!;
+ tempCtx.putImageData(adjustedData, 0, 0);
+
+ this.applyBrushMask(tempCtx, size, this.settings.hardness);
+
+ outputCtx.save();
+ outputCtx.globalAlpha = this.settings.opacity;
+ outputCtx.drawImage(tempCanvas, targetX, targetY);
+ outputCtx.restore();
+ }
+
+ applyStroke(
+ outputCtx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D,
+ stroke: SpongeStroke
+ ): void {
+ const { points, settings } = stroke;
+ if (points.length < 1) return;
+
+ const originalSettings = { ...this.settings };
+ this.settings = { ...settings };
+
+ const spacingPx = Math.max(1, (settings.size * settings.spacing) / 100);
+
+ for (let i = 0; i < points.length; i++) {
+ const point = points[i];
+
+ if (i > 0) {
+ const prev = points[i - 1];
+ const dx = point.x - prev.x;
+ const dy = point.y - prev.y;
+ const distance = Math.sqrt(dx * dx + dy * dy);
+ const steps = Math.ceil(distance / spacingPx);
+
+ for (let step = 0; step < steps; step++) {
+ const t = step / steps;
+ const interpX = prev.x + dx * t;
+ const interpY = prev.y + dy * t;
+ const interpPressure = prev.pressure + (point.pressure - prev.pressure) * t;
+
+ this.apply(outputCtx, interpX, interpY, interpPressure);
+ }
+ }
+
+ this.apply(outputCtx, point.x, point.y, point.pressure);
+ }
+
+ this.settings = originalSettings;
+ }
+
+ private adjustSaturation(imageData: ImageData, pressure: number): ImageData {
+ const data = imageData.data;
+ const flow = this.settings.flow * pressure;
+ const isSaturate = this.settings.mode === 'saturate';
+
+ for (let i = 0; i < data.length; i += 4) {
+ const r = data[i];
+ const g = data[i + 1];
+ const b = data[i + 2];
+
+ const { h, s, l } = this.rgbToHsl(r, g, b);
+
+ let newS: number;
+ if (isSaturate) {
+ if (this.settings.vibrance) {
+ const saturationWeight = 1 - s;
+ newS = s + (1 - s) * flow * saturationWeight;
+ } else {
+ newS = Math.min(1, s + (1 - s) * flow);
+ }
+ } else {
+ if (this.settings.vibrance) {
+ const saturationWeight = s;
+ newS = s - s * flow * saturationWeight;
+ } else {
+ newS = Math.max(0, s - s * flow);
+ }
+ }
+
+ const { r: newR, g: newG, b: newB } = this.hslToRgb(h, newS, l);
+
+ data[i] = newR;
+ data[i + 1] = newG;
+ data[i + 2] = newB;
+ }
+
+ return imageData;
+ }
+
+ private rgbToHsl(r: number, g: number, b: number): { h: number; s: number; l: number } {
+ r /= 255;
+ g /= 255;
+ b /= 255;
+
+ const max = Math.max(r, g, b);
+ const min = Math.min(r, g, b);
+ const l = (max + min) / 2;
+
+ if (max === min) {
+ return { h: 0, s: 0, l };
+ }
+
+ const d = max - min;
+ const s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
+
+ let h: number;
+ switch (max) {
+ case r:
+ h = ((g - b) / d + (g < b ? 6 : 0)) / 6;
+ break;
+ case g:
+ h = ((b - r) / d + 2) / 6;
+ break;
+ default:
+ h = ((r - g) / d + 4) / 6;
+ break;
+ }
+
+ return { h, s, l };
+ }
+
+ private hslToRgb(h: number, s: number, l: number): { r: number; g: number; b: number } {
+ if (s === 0) {
+ const gray = Math.round(l * 255);
+ return { r: gray, g: gray, b: gray };
+ }
+
+ const hue2rgb = (p: number, q: number, t: number): number => {
+ if (t < 0) t += 1;
+ if (t > 1) t -= 1;
+ if (t < 1 / 6) return p + (q - p) * 6 * t;
+ if (t < 1 / 2) return q;
+ if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
+ return p;
+ };
+
+ const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
+ const p = 2 * l - q;
+
+ return {
+ r: Math.round(hue2rgb(p, q, h + 1 / 3) * 255),
+ g: Math.round(hue2rgb(p, q, h) * 255),
+ b: Math.round(hue2rgb(p, q, h - 1 / 3) * 255),
+ };
+ }
+
+ private applyBrushMask(ctx: OffscreenCanvasRenderingContext2D, size: number, hardness: number): void {
+ const imageData = ctx.getImageData(0, 0, size, size);
+ const data = imageData.data;
+ const center = size / 2;
+ const radius = size / 2;
+ const hardnessNorm = hardness / 100;
+
+ for (let y = 0; y < size; y++) {
+ for (let x = 0; x < size; x++) {
+ const dx = x - center;
+ const dy = y - center;
+ const distance = Math.sqrt(dx * dx + dy * dy);
+ const normalizedDist = distance / radius;
+
+ let alpha = 1;
+ if (normalizedDist > hardnessNorm) {
+ alpha = 1 - (normalizedDist - hardnessNorm) / (1 - hardnessNorm);
+ alpha = Math.max(0, Math.min(1, alpha));
+ }
+ if (normalizedDist > 1) {
+ alpha = 0;
+ }
+
+ const idx = (y * size + x) * 4;
+ data[idx + 3] = Math.round(data[idx + 3] * alpha);
+ }
+ }
+
+ ctx.putImageData(imageData, 0, 0);
+ }
+
+ getSettings(): SpongeSettings {
+ return { ...this.settings };
+ }
+
+ updateSettings(settings: Partial<SpongeSettings>): void {
+ this.settings = { ...this.settings, ...settings };
+ }
+
+ isActiveStroke(): boolean {
+ return this.isActive;
+ }
+}
diff --git a/apps/image/src/tools/retouch/spot-healing.ts b/apps/image/src/tools/retouch/spot-healing.ts
new file mode 100644
index 00000000..1e5d90f8
--- /dev/null
+++ b/apps/image/src/tools/retouch/spot-healing.ts
@@ -0,0 +1,348 @@
+import { BrushSettings, DEFAULT_BRUSH_SETTINGS } from '../brush/brush-engine';
+
+export type SpotHealingType = 'proximity-match' | 'content-aware' | 'create-texture';
+
+export interface SpotHealingSettings extends BrushSettings {
+ type: SpotHealingType;
+ sampleAllLayers: boolean;
+}
+
+export const DEFAULT_SPOT_HEALING_SETTINGS: SpotHealingSettings = {
+ ...DEFAULT_BRUSH_SETTINGS,
+ type: 'content-aware',
+ sampleAllLayers: false,
+};
+
+interface PatchCandidate {
+ x: number;
+ y: number;
+ score: number;
+}
+
+export class SpotHealingTool {
+ private settings: SpotHealingSettings;
+ private canvas: OffscreenCanvas | null = null;
+ private ctx: OffscreenCanvasRenderingContext2D | null = null;
+
+ constructor(settings: Partial<SpotHealingSettings> = {}) {
+ this.settings = { ...DEFAULT_SPOT_HEALING_SETTINGS, ...settings };
+ }
+
+ setCanvas(canvas: OffscreenCanvas): void {
+ this.canvas = canvas;
+ this.ctx = canvas.getContext('2d', { willReadFrequently: true });
+ }
+
+ heal(
+ outputCtx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D,
+ x: number,
+ y: number
+ ): void {
+ if (!this.canvas || !this.ctx) return;
+
+ const size = Math.ceil(this.settings.size);
+ const halfSize = size / 2;
+
+ const targetX = Math.floor(x - halfSize);
+ const targetY = Math.floor(y - halfSize);
+
+ if (
+ targetX < 0 ||
+ targetY < 0 ||
+ targetX + size > this.canvas.width ||
+ targetY + size > this.canvas.height
+ ) {
+ return;
+ }
+
+ const targetData = this.ctx.getImageData(targetX, targetY, size, size);
+ let healedData: ImageData;
+
+ switch (this.settings.type) {
+ case 'proximity-match':
+ healedData = this.proximityMatch(targetX, targetY, size, targetData);
+ break;
+ case 'create-texture':
+ healedData = this.createTexture(targetX, targetY, size, targetData);
+ break;
+ case 'content-aware':
+ default:
+ healedData = this.contentAwareHeal(targetX, targetY, size, targetData);
+ break;
+ }
+
+ const tempCanvas = new OffscreenCanvas(size, size);
+ const tempCtx = tempCanvas.getContext('2d')!;
+ tempCtx.putImageData(healedData, 0, 0);
+
+ this.applyBrushMask(tempCtx, size, this.settings.hardness);
+
+ outputCtx.save();
+ outputCtx.globalAlpha = this.settings.opacity;
+ outputCtx.drawImage(tempCanvas, targetX, targetY);
+ outputCtx.restore();
+ }
+
+ private proximityMatch(
+ targetX: number,
+ targetY: number,
+ size: number,
+ _targetData: ImageData
+ ): ImageData {
+ if (!this.canvas || !this.ctx) {
+ return new ImageData(size, size);
+ }
+
+ const searchRadius = size * 2;
+ const candidates: PatchCandidate[] = [];
+
+ for (let dy = -searchRadius; dy <= searchRadius; dy += size / 2) {
+ for (let dx = -searchRadius; dx <= searchRadius; dx += size / 2) {
+ if (Math.abs(dx) < size && Math.abs(dy) < size) continue;
+
+ const sx = targetX + dx;
+ const sy = targetY + dy;
+
+ if (
+ sx < 0 ||
+ sy < 0 ||
+ sx + size > this.canvas.width ||
+ sy + size > this.canvas.height
+ ) {
+ continue;
+ }
+
+ const distance = Math.sqrt(dx * dx + dy * dy);
+ candidates.push({ x: sx, y: sy, score: 1 / distance });
+ }
+ }
+
+ if (candidates.length === 0) {
+ return this.ctx.getImageData(targetX, targetY, size, size);
+ }
+
+ candidates.sort((a, b) => b.score - a.score);
+ const best = candidates[0];
+
+ const sourceData = this.ctx.getImageData(best.x, best.y, size, size);
+ const targetSample = this.ctx.getImageData(targetX, targetY, size, size);
+
+ return this.blendWithColorMatch(sourceData, targetSample, size);
+ }
+
+ private contentAwareHeal(
+ _targetX: number,
+ _targetY: number,
+ size: number,
+ targetData: ImageData
+ ): ImageData {
+ if (!this.canvas || !this.ctx) {
+ return new ImageData(size, size);
+ }
+
+ const result = new ImageData(size, size);
+ const outData = result.data;
+ const tgtData = targetData.data;
+
+ const borderPixels: Array<{ x: number; y: number; r: number; g: number; b: number }> = [];
+
+ for (let y = 0; y < size; y++) {
+ for (let x = 0; x < size; x++) {
+ const dx = x - size / 2;
+ const dy = y - size / 2;
+ const dist = Math.sqrt(dx * dx + dy * dy);
+
+ if (dist > size / 2 - 2 && dist <= size / 2) {
+ const idx = (y * size + x) * 4;
+ borderPixels.push({
+ x,
+ y,
+ r: tgtData[idx],
+ g: tgtData[idx + 1],
+ b: tgtData[idx + 2],
+ });
+ }
+ }
+ }
+
+ for (let y = 0; y < size; y++) {
+ for (let x = 0; x < size; x++) {
+ const idx = (y * size + x) * 4;
+ const dx = x - size / 2;
+ const dy = y - size / 2;
+ const dist = Math.sqrt(dx * dx + dy * dy);
+
+ if (dist > size / 2) {
+ outData[idx] = tgtData[idx];
+ outData[idx + 1] = tgtData[idx + 1];
+ outData[idx + 2] = tgtData[idx + 2];
+ outData[idx + 3] = tgtData[idx + 3];
+ continue;
+ }
+
+ let totalWeight = 0;
+ let r = 0, g = 0, b = 0;
+
+ for (const border of borderPixels) {
+ const bdx = x - border.x;
+ const bdy = y - border.y;
+ const distance = Math.sqrt(bdx * bdx + bdy * bdy);
+ const weight = 1 / (distance * distance + 1);
+
+ r += border.r * weight;
+ g += border.g * weight;
+ b += border.b * weight;
+ totalWeight += weight;
+ }
+
+ if (totalWeight > 0) {
+ outData[idx] = Math.round(r / totalWeight);
+ outData[idx + 1] = Math.round(g / totalWeight);
+ outData[idx + 2] = Math.round(b / totalWeight);
+ } else {
+ outData[idx] = tgtData[idx];
+ outData[idx + 1] = tgtData[idx + 1];
+ outData[idx + 2] = tgtData[idx + 2];
+ }
+ outData[idx + 3] = 255;
+ }
+ }
+
+ return result;
+ }
+
+ private createTexture(
+ targetX: number,
+ targetY: number,
+ size: number,
+ _targetData: ImageData
+ ): ImageData {
+ if (!this.canvas || !this.ctx) {
+ return new ImageData(size, size);
+ }
+
+ const sampleSize = size;
+ const samples: ImageData[] = [];
+
+ const offsets = [
+ { x: -sampleSize, y: -sampleSize },
+ { x: sampleSize, y: -sampleSize },
+ { x: -sampleSize, y: sampleSize },
+ { x: sampleSize, y: sampleSize },
+ ];
+
+ for (const offset of offsets) {
+ const sx = targetX + offset.x;
+ const sy = targetY + offset.y;
+
+ if (
+ sx >= 0 &&
+ sy >= 0 &&
+ sx + size <= this.canvas.width &&
+ sy + size <= this.canvas.height
+ ) {
+ samples.push(this.ctx.getImageData(sx, sy, size, size));
+ }
+ }
+
+ if (samples.length === 0) {
+ return this.ctx.getImageData(targetX, targetY, size, size);
+ }
+
+ const result = new ImageData(size, size);
+ const outData = result.data;
+
+ for (let i = 0; i < outData.length; i += 4) {
+ let r = 0, g = 0, b = 0, a = 0;
+
+ for (const sample of samples) {
+ r += sample.data[i];
+ g += sample.data[i + 1];
+ b += sample.data[i + 2];
+ a += sample.data[i + 3];
+ }
+
+ outData[i] = Math.round(r / samples.length);
+ outData[i + 1] = Math.round(g / samples.length);
+ outData[i + 2] = Math.round(b / samples.length);
+ outData[i + 3] = Math.round(a / samples.length);
+ }
+
+ return result;
+ }
+
+ private blendWithColorMatch(source: ImageData, target: ImageData, size: number): ImageData {
+ const result = new ImageData(size, size);
+ const srcData = source.data;
+ const tgtData = target.data;
+ const outData = result.data;
+
+ const srcAvg = this.calculateAverage(srcData);
+ const tgtAvg = this.calculateAverage(tgtData);
+
+ for (let i = 0; i < srcData.length; i += 4) {
+ outData[i] = Math.max(0, Math.min(255, srcData[i] - srcAvg[0] + tgtAvg[0]));
+ outData[i + 1] = Math.max(0, Math.min(255, srcData[i + 1] - srcAvg[1] + tgtAvg[1]));
+ outData[i + 2] = Math.max(0, Math.min(255, srcData[i + 2] - srcAvg[2] + tgtAvg[2]));
+ outData[i + 3] = srcData[i + 3];
+ }
+
+ return result;
+ }
+
+ private calculateAverage(data: Uint8ClampedArray): [number, number, number] {
+ let r = 0, g = 0, b = 0;
+ let count = 0;
+
+ for (let i = 0; i < data.length; i += 4) {
+ if (data[i + 3] > 0) {
+ r += data[i];
+ g += data[i + 1];
+ b += data[i + 2];
+ count++;
+ }
+ }
+
+ if (count === 0) return [128, 128, 128];
+ return [r / count, g / count, b / count];
+ }
+
+ private applyBrushMask(ctx: OffscreenCanvasRenderingContext2D, size: number, hardness: number): void {
+ const imageData = ctx.getImageData(0, 0, size, size);
+ const data = imageData.data;
+ const center = size / 2;
+ const radius = size / 2;
+ const hardnessNorm = hardness / 100;
+
+ for (let y = 0; y < size; y++) {
+ for (let x = 0; x < size; x++) {
+ const dx = x - center;
+ const dy = y - center;
+ const distance = Math.sqrt(dx * dx + dy * dy);
+ const normalizedDist = distance / radius;
+
+ let alpha = 1;
+ if (normalizedDist > hardnessNorm) {
+ alpha = 1 - (normalizedDist - hardnessNorm) / (1 - hardnessNorm);
+ alpha = Math.max(0, Math.min(1, alpha));
+ }
+ if (normalizedDist > 1) {
+ alpha = 0;
+ }
+
+ const idx = (y * size + x) * 4;
+ data[idx + 3] = Math.round(data[idx + 3] * alpha);
+ }
+ }
+
+ ctx.putImageData(imageData, 0, 0);
+ }
+
+ getSettings(): SpotHealingSettings {
+ return { ...this.settings };
+ }
+
+ updateSettings(settings: Partial<SpotHealingSettings>): void {
+ this.settings = { ...this.settings, ...settings };
+ }
+}