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 6 transform tools

Augustus Otucc6d28c86584
diff --git a/apps/image/src/tools/transform/free-transform.ts b/apps/image/src/tools/transform/free-transform.ts
new file mode 100644
index 00000000..9cf3957f
--- /dev/null
+++ b/apps/image/src/tools/transform/free-transform.ts
@@ -0,0 +1,592 @@
+export interface TransformMatrix {
+ a: number;
+ b: number;
+ c: number;
+ d: number;
+ e: number;
+ f: number;
+}
+
+export interface TransformState {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+ rotation: number;
+ scaleX: number;
+ scaleY: number;
+ skewX: number;
+ skewY: number;
+ originX: number;
+ originY: number;
+}
+
+export interface TransformHandle {
+ type: 'corner' | 'edge' | 'rotation' | 'origin';
+ position: 'nw' | 'n' | 'ne' | 'e' | 'se' | 's' | 'sw' | 'w' | 'center';
+ x: number;
+ y: number;
+}
+
+export interface TransformBounds {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+ corners: { nw: Point; ne: Point; se: Point; sw: Point };
+}
+
+interface Point {
+ x: number;
+ y: number;
+}
+
+export const DEFAULT_TRANSFORM: TransformState = {
+ x: 0,
+ y: 0,
+ width: 100,
+ height: 100,
+ rotation: 0,
+ scaleX: 1,
+ scaleY: 1,
+ skewX: 0,
+ skewY: 0,
+ originX: 0.5,
+ originY: 0.5,
+};
+
+export function createIdentityMatrix(): TransformMatrix {
+ return { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 };
+}
+
+export function multiplyMatrices(m1: TransformMatrix, m2: TransformMatrix): TransformMatrix {
+ return {
+ a: m1.a * m2.a + m1.c * m2.b,
+ b: m1.b * m2.a + m1.d * m2.b,
+ c: m1.a * m2.c + m1.c * m2.d,
+ d: m1.b * m2.c + m1.d * m2.d,
+ e: m1.a * m2.e + m1.c * m2.f + m1.e,
+ f: m1.b * m2.e + m1.d * m2.f + m1.f,
+ };
+}
+
+export function invertMatrix(m: TransformMatrix): TransformMatrix | null {
+ const det = m.a * m.d - m.b * m.c;
+ if (Math.abs(det) < 1e-10) return null;
+
+ const invDet = 1 / det;
+ return {
+ a: m.d * invDet,
+ b: -m.b * invDet,
+ c: -m.c * invDet,
+ d: m.a * invDet,
+ e: (m.c * m.f - m.d * m.e) * invDet,
+ f: (m.b * m.e - m.a * m.f) * invDet,
+ };
+}
+
+export function transformPoint(point: Point, matrix: TransformMatrix): Point {
+ return {
+ x: matrix.a * point.x + matrix.c * point.y + matrix.e,
+ y: matrix.b * point.x + matrix.d * point.y + matrix.f,
+ };
+}
+
+export function createTranslateMatrix(tx: number, ty: number): TransformMatrix {
+ return { a: 1, b: 0, c: 0, d: 1, e: tx, f: ty };
+}
+
+export function createScaleMatrix(sx: number, sy: number): TransformMatrix {
+ return { a: sx, b: 0, c: 0, d: sy, e: 0, f: 0 };
+}
+
+export function createRotateMatrix(angle: number): TransformMatrix {
+ const cos = Math.cos(angle);
+ const sin = Math.sin(angle);
+ return { a: cos, b: sin, c: -sin, d: cos, e: 0, f: 0 };
+}
+
+export function createSkewMatrix(skewX: number, skewY: number): TransformMatrix {
+ return {
+ a: 1,
+ b: Math.tan(skewY),
+ c: Math.tan(skewX),
+ d: 1,
+ e: 0,
+ f: 0,
+ };
+}
+
+export function stateToMatrix(state: TransformState): TransformMatrix {
+ const { x, y, width, height, rotation, scaleX, scaleY, skewX, skewY, originX, originY } = state;
+
+ const ox = x + width * originX;
+ const oy = y + height * originY;
+
+ let matrix = createIdentityMatrix();
+
+ matrix = multiplyMatrices(matrix, createTranslateMatrix(ox, oy));
+ matrix = multiplyMatrices(matrix, createRotateMatrix(rotation));
+ matrix = multiplyMatrices(matrix, createSkewMatrix(skewX, skewY));
+ matrix = multiplyMatrices(matrix, createScaleMatrix(scaleX, scaleY));
+ matrix = multiplyMatrices(matrix, createTranslateMatrix(-ox, -oy));
+ matrix = multiplyMatrices(matrix, createTranslateMatrix(x, y));
+
+ return matrix;
+}
+
+export function matrixToState(matrix: TransformMatrix, width: number, height: number): TransformState {
+ const scaleX = Math.sqrt(matrix.a * matrix.a + matrix.b * matrix.b);
+ const scaleY = Math.sqrt(matrix.c * matrix.c + matrix.d * matrix.d);
+
+ const rotation = Math.atan2(matrix.b, matrix.a);
+
+ const cos = Math.cos(-rotation);
+ const sin = Math.sin(-rotation);
+ const skewX = Math.atan2(matrix.c * cos + matrix.d * sin, matrix.a * cos + matrix.b * sin);
+ const skewY = 0;
+
+ return {
+ x: matrix.e,
+ y: matrix.f,
+ width,
+ height,
+ rotation,
+ scaleX,
+ scaleY,
+ skewX,
+ skewY,
+ originX: 0.5,
+ originY: 0.5,
+ };
+}
+
+export function getTransformBounds(state: TransformState): TransformBounds {
+ const { width, height } = state;
+ const matrix = stateToMatrix(state);
+
+ const corners = {
+ nw: transformPoint({ x: 0, y: 0 }, matrix),
+ ne: transformPoint({ x: width, y: 0 }, matrix),
+ se: transformPoint({ x: width, y: height }, matrix),
+ sw: transformPoint({ x: 0, y: height }, matrix),
+ };
+
+ const xs = [corners.nw.x, corners.ne.x, corners.se.x, corners.sw.x];
+ const ys = [corners.nw.y, corners.ne.y, corners.se.y, corners.sw.y];
+
+ const minX = Math.min(...xs);
+ const maxX = Math.max(...xs);
+ const minY = Math.min(...ys);
+ const maxY = Math.max(...ys);
+
+ return {
+ x: minX,
+ y: minY,
+ width: maxX - minX,
+ height: maxY - minY,
+ corners,
+ };
+}
+
+export function getTransformHandles(state: TransformState, _handleSize: number = 8): TransformHandle[] {
+ const bounds = getTransformBounds(state);
+ const { corners } = bounds;
+
+ const midTop = {
+ x: (corners.nw.x + corners.ne.x) / 2,
+ y: (corners.nw.y + corners.ne.y) / 2,
+ };
+ const midRight = {
+ x: (corners.ne.x + corners.se.x) / 2,
+ y: (corners.ne.y + corners.se.y) / 2,
+ };
+ const midBottom = {
+ x: (corners.se.x + corners.sw.x) / 2,
+ y: (corners.se.y + corners.sw.y) / 2,
+ };
+ const midLeft = {
+ x: (corners.sw.x + corners.nw.x) / 2,
+ y: (corners.sw.y + corners.nw.y) / 2,
+ };
+ const center = {
+ x: (corners.nw.x + corners.se.x) / 2,
+ y: (corners.nw.y + corners.se.y) / 2,
+ };
+
+ const rotationOffset = 20;
+ const rotationHandle = {
+ x: midTop.x - Math.sin(state.rotation) * rotationOffset,
+ y: midTop.y - Math.cos(state.rotation) * rotationOffset,
+ };
+
+ return [
+ { type: 'corner', position: 'nw', x: corners.nw.x, y: corners.nw.y },
+ { type: 'edge', position: 'n', x: midTop.x, y: midTop.y },
+ { type: 'corner', position: 'ne', x: corners.ne.x, y: corners.ne.y },
+ { type: 'edge', position: 'e', x: midRight.x, y: midRight.y },
+ { type: 'corner', position: 'se', x: corners.se.x, y: corners.se.y },
+ { type: 'edge', position: 's', x: midBottom.x, y: midBottom.y },
+ { type: 'corner', position: 'sw', x: corners.sw.x, y: corners.sw.y },
+ { type: 'edge', position: 'w', x: midLeft.x, y: midLeft.y },
+ { type: 'rotation', position: 'n', x: rotationHandle.x, y: rotationHandle.y },
+ { type: 'origin', position: 'center', x: center.x, y: center.y },
+ ];
+}
+
+export function hitTestHandle(
+ x: number,
+ y: number,
+ handles: TransformHandle[],
+ threshold: number = 10
+): TransformHandle | null {
+ for (const handle of handles) {
+ const dist = Math.hypot(x - handle.x, y - handle.y);
+ if (dist <= threshold) {
+ return handle;
+ }
+ }
+ return null;
+}
+
+export function scaleFromHandle(
+ state: TransformState,
+ handle: TransformHandle,
+ dx: number,
+ dy: number,
+ preserveAspect: boolean = false,
+ fromCenter: boolean = false
+): TransformState {
+ const { x, y, width, height, scaleX, scaleY, rotation } = state;
+
+ const cos = Math.cos(-rotation);
+ const sin = Math.sin(-rotation);
+ const localDx = dx * cos - dy * sin;
+ const localDy = dx * sin + dy * cos;
+
+ let newScaleX = scaleX;
+ let newScaleY = scaleY;
+ let newX = x;
+ let newY = y;
+
+ switch (handle.position) {
+ case 'nw':
+ newScaleX = scaleX - localDx / width;
+ newScaleY = scaleY - localDy / height;
+ if (!fromCenter) {
+ newX = x + dx;
+ newY = y + dy;
+ }
+ break;
+ case 'ne':
+ newScaleX = scaleX + localDx / width;
+ newScaleY = scaleY - localDy / height;
+ if (!fromCenter) {
+ newY = y + dy;
+ }
+ break;
+ case 'se':
+ newScaleX = scaleX + localDx / width;
+ newScaleY = scaleY + localDy / height;
+ break;
+ case 'sw':
+ newScaleX = scaleX - localDx / width;
+ newScaleY = scaleY + localDy / height;
+ if (!fromCenter) {
+ newX = x + dx;
+ }
+ break;
+ case 'n':
+ newScaleY = scaleY - localDy / height;
+ if (!fromCenter) {
+ newY = y + dy;
+ }
+ break;
+ case 's':
+ newScaleY = scaleY + localDy / height;
+ break;
+ case 'e':
+ newScaleX = scaleX + localDx / width;
+ break;
+ case 'w':
+ newScaleX = scaleX - localDx / width;
+ if (!fromCenter) {
+ newX = x + dx;
+ }
+ break;
+ }
+
+ if (preserveAspect && handle.type === 'corner') {
+ const avgScale = (Math.abs(newScaleX) + Math.abs(newScaleY)) / 2;
+ newScaleX = avgScale * Math.sign(newScaleX || 1);
+ newScaleY = avgScale * Math.sign(newScaleY || 1);
+ }
+
+ if (fromCenter) {
+ const bounds = getTransformBounds(state);
+ const centerX = (bounds.corners.nw.x + bounds.corners.se.x) / 2;
+ const centerY = (bounds.corners.nw.y + bounds.corners.se.y) / 2;
+
+ const newState = { ...state, scaleX: newScaleX, scaleY: newScaleY };
+ const newBounds = getTransformBounds(newState);
+ const newCenterX = (newBounds.corners.nw.x + newBounds.corners.se.x) / 2;
+ const newCenterY = (newBounds.corners.nw.y + newBounds.corners.se.y) / 2;
+
+ newX = state.x + (centerX - newCenterX);
+ newY = state.y + (centerY - newCenterY);
+ }
+
+ return {
+ ...state,
+ x: newX,
+ y: newY,
+ scaleX: newScaleX,
+ scaleY: newScaleY,
+ };
+}
+
+export function rotateFromHandle(
+ state: TransformState,
+ _cx: number,
+ _cy: number,
+ startAngle: number,
+ currentAngle: number,
+ snap: boolean = false
+): TransformState {
+ let deltaAngle = currentAngle - startAngle;
+
+ if (snap) {
+ const snapAngle = Math.PI / 12;
+ deltaAngle = Math.round(deltaAngle / snapAngle) * snapAngle;
+ }
+
+ return {
+ ...state,
+ rotation: state.rotation + deltaAngle,
+ };
+}
+
+export function skewFromHandle(
+ state: TransformState,
+ handle: TransformHandle,
+ dx: number,
+ dy: number
+): TransformState {
+ const { width, height } = state;
+
+ let newSkewX = state.skewX;
+ let newSkewY = state.skewY;
+
+ if (handle.position === 'n' || handle.position === 's') {
+ newSkewX = Math.atan(dx / height) + state.skewX;
+ } else if (handle.position === 'e' || handle.position === 'w') {
+ newSkewY = Math.atan(dy / width) + state.skewY;
+ }
+
+ return {
+ ...state,
+ skewX: newSkewX,
+ skewY: newSkewY,
+ };
+}
+
+export function moveOrigin(
+ state: TransformState,
+ newOriginX: number,
+ newOriginY: number
+): TransformState {
+ return {
+ ...state,
+ originX: Math.max(0, Math.min(1, newOriginX)),
+ originY: Math.max(0, Math.min(1, newOriginY)),
+ };
+}
+
+export function applyTransformToImageData(
+ imageData: ImageData,
+ state: TransformState,
+ interpolation: 'nearest' | 'bilinear' = 'bilinear'
+): ImageData {
+ const { width: srcWidth, height: srcHeight, data: srcData } = imageData;
+ const bounds = getTransformBounds(state);
+
+ const dstWidth = Math.ceil(bounds.width);
+ const dstHeight = Math.ceil(bounds.height);
+ const dstData = new Uint8ClampedArray(dstWidth * dstHeight * 4);
+
+ const matrix = stateToMatrix(state);
+ const invMatrix = invertMatrix(matrix);
+
+ if (!invMatrix) {
+ return new ImageData(dstData, dstWidth, dstHeight);
+ }
+
+ for (let dstY = 0; dstY < dstHeight; dstY++) {
+ for (let dstX = 0; dstX < dstWidth; dstX++) {
+ const worldX = bounds.x + dstX;
+ const worldY = bounds.y + dstY;
+
+ const srcPoint = transformPoint({ x: worldX, y: worldY }, invMatrix);
+
+ if (srcPoint.x < 0 || srcPoint.x >= srcWidth || srcPoint.y < 0 || srcPoint.y >= srcHeight) {
+ continue;
+ }
+
+ const dstIdx = (dstY * dstWidth + dstX) * 4;
+
+ if (interpolation === 'nearest') {
+ const srcX = Math.round(srcPoint.x);
+ const srcY = Math.round(srcPoint.y);
+ const srcIdx = (srcY * srcWidth + srcX) * 4;
+
+ dstData[dstIdx] = srcData[srcIdx];
+ dstData[dstIdx + 1] = srcData[srcIdx + 1];
+ dstData[dstIdx + 2] = srcData[srcIdx + 2];
+ dstData[dstIdx + 3] = srcData[srcIdx + 3];
+ } else {
+ const x0 = Math.floor(srcPoint.x);
+ const y0 = Math.floor(srcPoint.y);
+ const x1 = Math.min(x0 + 1, srcWidth - 1);
+ const y1 = Math.min(y0 + 1, srcHeight - 1);
+
+ const fx = srcPoint.x - x0;
+ const fy = srcPoint.y - y0;
+
+ const idx00 = (y0 * srcWidth + x0) * 4;
+ const idx10 = (y0 * srcWidth + x1) * 4;
+ const idx01 = (y1 * srcWidth + x0) * 4;
+ const idx11 = (y1 * srcWidth + x1) * 4;
+
+ for (let c = 0; c < 4; c++) {
+ const v00 = srcData[idx00 + c];
+ const v10 = srcData[idx10 + c];
+ const v01 = srcData[idx01 + c];
+ const v11 = srcData[idx11 + c];
+
+ const v = v00 * (1 - fx) * (1 - fy) + v10 * fx * (1 - fy) + v01 * (1 - fx) * fy + v11 * fx * fy;
+
+ dstData[dstIdx + c] = Math.round(v);
+ }
+ }
+ }
+ }
+
+ return new ImageData(dstData, dstWidth, dstHeight);
+}
+
+export function renderTransformBox(
+ ctx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D,
+ state: TransformState,
+ options: {
+ handleSize?: number;
+ lineColor?: string;
+ handleColor?: string;
+ handleFillColor?: string;
+ showOrigin?: boolean;
+ showRotationHandle?: boolean;
+ } = {}
+): void {
+ const {
+ handleSize = 8,
+ lineColor = '#0ea5e9',
+ handleColor = '#0ea5e9',
+ handleFillColor = '#ffffff',
+ showOrigin = true,
+ showRotationHandle = true,
+ } = options;
+
+ const bounds = getTransformBounds(state);
+ const handles = getTransformHandles(state, handleSize);
+
+ ctx.save();
+
+ ctx.strokeStyle = lineColor;
+ ctx.lineWidth = 1;
+ ctx.setLineDash([4, 4]);
+
+ ctx.beginPath();
+ ctx.moveTo(bounds.corners.nw.x, bounds.corners.nw.y);
+ ctx.lineTo(bounds.corners.ne.x, bounds.corners.ne.y);
+ ctx.lineTo(bounds.corners.se.x, bounds.corners.se.y);
+ ctx.lineTo(bounds.corners.sw.x, bounds.corners.sw.y);
+ ctx.closePath();
+ ctx.stroke();
+
+ ctx.setLineDash([]);
+
+ for (const handle of handles) {
+ if (handle.type === 'rotation' && !showRotationHandle) continue;
+ if (handle.type === 'origin' && !showOrigin) continue;
+
+ ctx.beginPath();
+
+ if (handle.type === 'rotation') {
+ const midTop = handles.find((h) => h.type === 'edge' && h.position === 'n');
+ if (midTop) {
+ ctx.strokeStyle = lineColor;
+ ctx.moveTo(midTop.x, midTop.y);
+ ctx.lineTo(handle.x, handle.y);
+ ctx.stroke();
+ }
+
+ ctx.beginPath();
+ ctx.arc(handle.x, handle.y, handleSize / 2, 0, Math.PI * 2);
+ ctx.fillStyle = handleFillColor;
+ ctx.fill();
+ ctx.strokeStyle = handleColor;
+ ctx.stroke();
+ } else if (handle.type === 'origin') {
+ ctx.strokeStyle = handleColor;
+ ctx.lineWidth = 1.5;
+ const size = handleSize / 2;
+ ctx.moveTo(handle.x - size, handle.y);
+ ctx.lineTo(handle.x + size, handle.y);
+ ctx.moveTo(handle.x, handle.y - size);
+ ctx.lineTo(handle.x, handle.y + size);
+ ctx.stroke();
+
+ ctx.beginPath();
+ ctx.arc(handle.x, handle.y, size, 0, Math.PI * 2);
+ ctx.stroke();
+ } else {
+ ctx.rect(
+ handle.x - handleSize / 2,
+ handle.y - handleSize / 2,
+ handleSize,
+ handleSize
+ );
+ ctx.fillStyle = handleFillColor;
+ ctx.fill();
+ ctx.strokeStyle = handleColor;
+ ctx.lineWidth = 1.5;
+ ctx.stroke();
+ }
+ }
+
+ ctx.restore();
+}
+
+export function getCursorForHandle(handle: TransformHandle | null, rotation: number = 0): string {
+ if (!handle) return 'default';
+
+ if (handle.type === 'rotation') return 'grab';
+ if (handle.type === 'origin') return 'move';
+
+ const cursors: Record<string, string[]> = {
+ corner: ['nwse-resize', 'nesw-resize', 'nwse-resize', 'nesw-resize'],
+ edge: ['ns-resize', 'ew-resize', 'ns-resize', 'ew-resize'],
+ };
+
+ const positions: Record<string, number> = {
+ nw: 0, ne: 1, se: 2, sw: 3,
+ n: 0, e: 1, s: 2, w: 3,
+ };
+
+ const baseCursors = cursors[handle.type];
+ const baseIndex = positions[handle.position] || 0;
+
+ const rotationSteps = Math.round((rotation * 4) / Math.PI) % 8;
+ const finalIndex = (baseIndex + Math.floor(rotationSteps / 2)) % baseCursors.length;
+
+ return baseCursors[finalIndex];
+}
diff --git a/apps/image/src/tools/transform/liquify.ts b/apps/image/src/tools/transform/liquify.ts
new file mode 100644
index 00000000..144270f4
--- /dev/null
+++ b/apps/image/src/tools/transform/liquify.ts
@@ -0,0 +1,503 @@
+export type LiquifyTool =
+ | 'push'
+ | 'twirl-clockwise'
+ | 'twirl-counterclockwise'
+ | 'pucker'
+ | 'bloat'
+ | 'push-left'
+ | 'freeze'
+ | 'thaw'
+ | 'reconstruct';
+
+export interface LiquifyBrush {
+ size: number;
+ pressure: number;
+ density: number;
+ rate: number;
+}
+
+export interface LiquifyState {
+ tool: LiquifyTool;
+ brush: LiquifyBrush;
+ meshSize: number;
+ showMesh: boolean;
+}
+
+export interface DisplacementMesh {
+ width: number;
+ height: number;
+ cellSize: number;
+ cols: number;
+ rows: number;
+ displacements: Float32Array;
+ frozen: Uint8Array;
+}
+
+export const DEFAULT_LIQUIFY_BRUSH: LiquifyBrush = {
+ size: 100,
+ pressure: 50,
+ density: 50,
+ rate: 80,
+};
+
+export const DEFAULT_LIQUIFY_STATE: LiquifyState = {
+ tool: 'push',
+ brush: DEFAULT_LIQUIFY_BRUSH,
+ meshSize: 8,
+ showMesh: false,
+};
+
+export function createDisplacementMesh(
+ width: number,
+ height: number,
+ cellSize: number = 8
+): DisplacementMesh {
+ const cols = Math.ceil(width / cellSize) + 1;
+ const rows = Math.ceil(height / cellSize) + 1;
+
+ return {
+ width,
+ height,
+ cellSize,
+ cols,
+ rows,
+ displacements: new Float32Array(cols * rows * 2),
+ frozen: new Uint8Array(cols * rows),
+ };
+}
+
+export function resetMesh(mesh: DisplacementMesh): DisplacementMesh {
+ return {
+ ...mesh,
+ displacements: new Float32Array(mesh.cols * mesh.rows * 2),
+ frozen: new Uint8Array(mesh.cols * mesh.rows),
+ };
+}
+
+function getDisplacement(
+ mesh: DisplacementMesh,
+ col: number,
+ row: number
+): { dx: number; dy: number } {
+ if (col < 0 || col >= mesh.cols || row < 0 || row >= mesh.rows) {
+ return { dx: 0, dy: 0 };
+ }
+
+ const idx = (row * mesh.cols + col) * 2;
+ return {
+ dx: mesh.displacements[idx],
+ dy: mesh.displacements[idx + 1],
+ };
+}
+
+function setDisplacement(
+ mesh: DisplacementMesh,
+ col: number,
+ row: number,
+ dx: number,
+ dy: number
+): void {
+ if (col < 0 || col >= mesh.cols || row < 0 || row >= mesh.rows) {
+ return;
+ }
+
+ const idx = (row * mesh.cols + col) * 2;
+ const frozenIdx = row * mesh.cols + col;
+
+ if (mesh.frozen[frozenIdx]) {
+ return;
+ }
+
+ mesh.displacements[idx] = dx;
+ mesh.displacements[idx + 1] = dy;
+}
+
+function isFrozen(mesh: DisplacementMesh, col: number, row: number): boolean {
+ if (col < 0 || col >= mesh.cols || row < 0 || row >= mesh.rows) {
+ return true;
+ }
+ return mesh.frozen[row * mesh.cols + col] === 1;
+}
+
+function setFrozen(mesh: DisplacementMesh, col: number, row: number, frozen: boolean): void {
+ if (col < 0 || col >= mesh.cols || row < 0 || row >= mesh.rows) {
+ return;
+ }
+ mesh.frozen[row * mesh.cols + col] = frozen ? 1 : 0;
+}
+
+function brushFalloff(distance: number, radius: number, density: number): number {
+ if (distance >= radius) return 0;
+
+ const normalized = distance / radius;
+ const densityFactor = density / 100;
+
+ return Math.pow(1 - Math.pow(normalized, 2), densityFactor * 2 + 0.5);
+}
+
+export function applyLiquifyStroke(
+ mesh: DisplacementMesh,
+ tool: LiquifyTool,
+ x: number,
+ y: number,
+ brush: LiquifyBrush,
+ prevX?: number,
+ prevY?: number
+): DisplacementMesh {
+ const newMesh = {
+ ...mesh,
+ displacements: new Float32Array(mesh.displacements),
+ frozen: new Uint8Array(mesh.frozen),
+ };
+
+ const radius = brush.size / 2;
+ const strength = (brush.pressure / 100) * (brush.rate / 100);
+
+ const minCol = Math.max(0, Math.floor((x - radius) / mesh.cellSize));
+ const maxCol = Math.min(mesh.cols - 1, Math.ceil((x + radius) / mesh.cellSize));
+ const minRow = Math.max(0, Math.floor((y - radius) / mesh.cellSize));
+ const maxRow = Math.min(mesh.rows - 1, Math.ceil((y + radius) / mesh.cellSize));
+
+ for (let row = minRow; row <= maxRow; row++) {
+ for (let col = minCol; col <= maxCol; col++) {
+ const cellX = col * mesh.cellSize;
+ const cellY = row * mesh.cellSize;
+ const distance = Math.hypot(cellX - x, cellY - y);
+
+ if (distance > radius) continue;
+ if (isFrozen(newMesh, col, row) && tool !== 'thaw') continue;
+
+ const falloff = brushFalloff(distance, radius, brush.density);
+ const current = getDisplacement(newMesh, col, row);
+
+ let dx = current.dx;
+ let dy = current.dy;
+
+ switch (tool) {
+ case 'push': {
+ if (prevX !== undefined && prevY !== undefined) {
+ const pushDx = (x - prevX) * strength * falloff;
+ const pushDy = (y - prevY) * strength * falloff;
+ dx += pushDx;
+ dy += pushDy;
+ }
+ break;
+ }
+
+ case 'twirl-clockwise':
+ case 'twirl-counterclockwise': {
+ const toCenterX = cellX - x;
+ const toCenterY = cellY - y;
+ const direction = tool === 'twirl-clockwise' ? 1 : -1;
+ const angle = direction * strength * falloff * 0.1;
+ const cos = Math.cos(angle);
+ const sin = Math.sin(angle);
+ const rotatedX = toCenterX * cos - toCenterY * sin;
+ const rotatedY = toCenterX * sin + toCenterY * cos;
+ dx += (rotatedX - toCenterX) * falloff;
+ dy += (rotatedY - toCenterY) * falloff;
+ break;
+ }
+
+ case 'pucker': {
+ const toCenterX = x - cellX;
+ const toCenterY = y - cellY;
+ dx += toCenterX * strength * falloff * 0.1;
+ dy += toCenterY * strength * falloff * 0.1;
+ break;
+ }
+
+ case 'bloat': {
+ const fromCenterX = cellX - x;
+ const fromCenterY = cellY - y;
+ dx += fromCenterX * strength * falloff * 0.1;
+ dy += fromCenterY * strength * falloff * 0.1;
+ break;
+ }
+
+ case 'push-left': {
+ if (prevX !== undefined && prevY !== undefined) {
+ const moveX = x - prevX;
+ const moveY = y - prevY;
+ const moveLen = Math.hypot(moveX, moveY);
+ if (moveLen > 0) {
+ const perpX = -moveY / moveLen;
+ const perpY = moveX / moveLen;
+ dx += perpX * moveLen * strength * falloff;
+ dy += perpY * moveLen * strength * falloff;
+ }
+ }
+ break;
+ }
+
+ case 'freeze': {
+ setFrozen(newMesh, col, row, true);
+ continue;
+ }
+
+ case 'thaw': {
+ setFrozen(newMesh, col, row, false);
+ continue;
+ }
+
+ case 'reconstruct': {
+ dx *= 1 - (strength * falloff * 0.5);
+ dy *= 1 - (strength * falloff * 0.5);
+ break;
+ }
+ }
+
+ setDisplacement(newMesh, col, row, dx, dy);
+ }
+ }
+
+ return newMesh;
+}
+
+function bilinearInterpolate(
+ mesh: DisplacementMesh,
+ x: number,
+ y: number
+): { dx: number; dy: number } {
+ const col = x / mesh.cellSize;
+ const row = y / mesh.cellSize;
+
+ const col0 = Math.floor(col);
+ const row0 = Math.floor(row);
+ const col1 = col0 + 1;
+ const row1 = row0 + 1;
+
+ const fx = col - col0;
+ const fy = row - row0;
+
+ const d00 = getDisplacement(mesh, col0, row0);
+ const d10 = getDisplacement(mesh, col1, row0);
+ const d01 = getDisplacement(mesh, col0, row1);
+ const d11 = getDisplacement(mesh, col1, row1);
+
+ return {
+ dx:
+ d00.dx * (1 - fx) * (1 - fy) +
+ d10.dx * fx * (1 - fy) +
+ d01.dx * (1 - fx) * fy +
+ d11.dx * fx * fy,
+ dy:
+ d00.dy * (1 - fx) * (1 - fy) +
+ d10.dy * fx * (1 - fy) +
+ d01.dy * (1 - fx) * fy +
+ d11.dy * fx * fy,
+ };
+}
+
+export function applyLiquify(
+ imageData: ImageData,
+ mesh: DisplacementMesh,
+ interpolation: 'nearest' | 'bilinear' = 'bilinear'
+): ImageData {
+ const { width, height, data } = imageData;
+ const resultData = new Uint8ClampedArray(data.length);
+
+ for (let y = 0; y < height; y++) {
+ for (let x = 0; x < width; x++) {
+ const displacement = bilinearInterpolate(mesh, x, y);
+ const srcX = x - displacement.dx;
+ const srcY = y - displacement.dy;
+
+ const dstIdx = (y * width + x) * 4;
+
+ if (srcX < 0 || srcX >= width - 1 || srcY < 0 || srcY >= height - 1) {
+ const clampedX = Math.max(0, Math.min(width - 1, Math.round(srcX)));
+ const clampedY = Math.max(0, Math.min(height - 1, Math.round(srcY)));
+ const srcIdx = (clampedY * width + clampedX) * 4;
+
+ resultData[dstIdx] = data[srcIdx];
+ resultData[dstIdx + 1] = data[srcIdx + 1];
+ resultData[dstIdx + 2] = data[srcIdx + 2];
+ resultData[dstIdx + 3] = data[srcIdx + 3];
+ continue;
+ }
+
+ if (interpolation === 'nearest') {
+ const roundedX = Math.round(srcX);
+ const roundedY = Math.round(srcY);
+ const srcIdx = (roundedY * width + roundedX) * 4;
+
+ resultData[dstIdx] = data[srcIdx];
+ resultData[dstIdx + 1] = data[srcIdx + 1];
+ resultData[dstIdx + 2] = data[srcIdx + 2];
+ resultData[dstIdx + 3] = data[srcIdx + 3];
+ } else {
+ const x0 = Math.floor(srcX);
+ const y0 = Math.floor(srcY);
+ const x1 = x0 + 1;
+ const y1 = y0 + 1;
+
+ const fx = srcX - x0;
+ const fy = srcY - y0;
+
+ const idx00 = (y0 * width + x0) * 4;
+ const idx10 = (y0 * width + x1) * 4;
+ const idx01 = (y1 * width + x0) * 4;
+ const idx11 = (y1 * width + x1) * 4;
+
+ for (let c = 0; c < 4; c++) {
+ const v =
+ data[idx00 + c] * (1 - fx) * (1 - fy) +
+ data[idx10 + c] * fx * (1 - fy) +
+ data[idx01 + c] * (1 - fx) * fy +
+ data[idx11 + c] * fx * fy;
+
+ resultData[dstIdx + c] = Math.round(v);
+ }
+ }
+ }
+ }
+
+ return new ImageData(resultData, width, height);
+}
+
+export function renderMesh(
+ ctx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D,
+ mesh: DisplacementMesh,
+ options: {
+ meshColor?: string;
+ frozenColor?: string;
+ showDisplaced?: boolean;
+ } = {}
+): void {
+ const { meshColor = 'rgba(100, 100, 255, 0.3)', frozenColor = 'rgba(255, 0, 0, 0.3)', showDisplaced = true } = options;
+
+ ctx.save();
+
+ ctx.strokeStyle = meshColor;
+ ctx.lineWidth = 0.5;
+
+ for (let row = 0; row < mesh.rows; row++) {
+ ctx.beginPath();
+ for (let col = 0; col < mesh.cols; col++) {
+ let x = col * mesh.cellSize;
+ let y = row * mesh.cellSize;
+
+ if (showDisplaced) {
+ const d = getDisplacement(mesh, col, row);
+ x += d.dx;
+ y += d.dy;
+ }
+
+ if (col === 0) {
+ ctx.moveTo(x, y);
+ } else {
+ ctx.lineTo(x, y);
+ }
+ }
+ ctx.stroke();
+ }
+
+ for (let col = 0; col < mesh.cols; col++) {
+ ctx.beginPath();
+ for (let row = 0; row < mesh.rows; row++) {
+ let x = col * mesh.cellSize;
+ let y = row * mesh.cellSize;
+
+ if (showDisplaced) {
+ const d = getDisplacement(mesh, col, row);
+ x += d.dx;
+ y += d.dy;
+ }
+
+ if (row === 0) {
+ ctx.moveTo(x, y);
+ } else {
+ ctx.lineTo(x, y);
+ }
+ }
+ ctx.stroke();
+ }
+
+ ctx.fillStyle = frozenColor;
+ for (let row = 0; row < mesh.rows; row++) {
+ for (let col = 0; col < mesh.cols; col++) {
+ if (isFrozen(mesh, col, row)) {
+ let x = col * mesh.cellSize;
+ let y = row * mesh.cellSize;
+
+ if (showDisplaced) {
+ const d = getDisplacement(mesh, col, row);
+ x += d.dx;
+ y += d.dy;
+ }
+
+ ctx.beginPath();
+ ctx.arc(x, y, 3, 0, Math.PI * 2);
+ ctx.fill();
+ }
+ }
+ }
+
+ ctx.restore();
+}
+
+export function renderBrush(
+ ctx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D,
+ x: number,
+ y: number,
+ brush: LiquifyBrush,
+ tool: LiquifyTool
+): void {
+ ctx.save();
+
+ const radius = brush.size / 2;
+
+ ctx.beginPath();
+ ctx.arc(x, y, radius, 0, Math.PI * 2);
+ ctx.strokeStyle = tool === 'freeze' ? '#ff6b6b' : tool === 'thaw' ? '#4ecdc4' : '#0ea5e9';
+ ctx.lineWidth = 1.5;
+ ctx.stroke();
+
+ const innerRadius = radius * (brush.density / 100);
+ ctx.beginPath();
+ ctx.arc(x, y, innerRadius, 0, Math.PI * 2);
+ ctx.strokeStyle = 'rgba(255, 255, 255, 0.5)';
+ ctx.lineWidth = 1;
+ ctx.stroke();
+
+ ctx.beginPath();
+ ctx.arc(x, y, 2, 0, Math.PI * 2);
+ ctx.fillStyle = '#ffffff';
+ ctx.fill();
+
+ ctx.restore();
+}
+
+export function smoothMesh(mesh: DisplacementMesh, iterations: number = 1): DisplacementMesh {
+ let result = { ...mesh, displacements: new Float32Array(mesh.displacements) };
+
+ for (let iter = 0; iter < iterations; iter++) {
+ const newDisplacements = new Float32Array(result.displacements);
+
+ for (let row = 1; row < mesh.rows - 1; row++) {
+ for (let col = 1; col < mesh.cols - 1; col++) {
+ if (isFrozen(result, col, row)) continue;
+
+ const neighbors = [
+ getDisplacement(result, col - 1, row),
+ getDisplacement(result, col + 1, row),
+ getDisplacement(result, col, row - 1),
+ getDisplacement(result, col, row + 1),
+ ];
+
+ const current = getDisplacement(result, col, row);
+ const avgDx = neighbors.reduce((sum, n) => sum + n.dx, 0) / 4;
+ const avgDy = neighbors.reduce((sum, n) => sum + n.dy, 0) / 4;
+
+ const idx = (row * mesh.cols + col) * 2;
+ newDisplacements[idx] = current.dx * 0.5 + avgDx * 0.5;
+ newDisplacements[idx + 1] = current.dy * 0.5 + avgDy * 0.5;
+ }
+ }
+
+ result.displacements = newDisplacements;
+ }
+
+ return result;
+}
diff --git a/apps/image/src/tools/transform/perspective.ts b/apps/image/src/tools/transform/perspective.ts
new file mode 100644
index 00000000..48109ed9
--- /dev/null
+++ b/apps/image/src/tools/transform/perspective.ts
@@ -0,0 +1,455 @@
+export interface PerspectiveCorners {
+ topLeft: { x: number; y: number };
+ topRight: { x: number; y: number };
+ bottomLeft: { x: number; y: number };
+ bottomRight: { x: number; y: number };
+}
+
+export interface PerspectiveMatrix {
+ m00: number;
+ m01: number;
+ m02: number;
+ m10: number;
+ m11: number;
+ m12: number;
+ m20: number;
+ m21: number;
+ m22: number;
+}
+
+export function createPerspectiveCornersFromRect(
+ x: number,
+ y: number,
+ width: number,
+ height: number
+): PerspectiveCorners {
+ return {
+ topLeft: { x, y },
+ topRight: { x: x + width, y },
+ bottomLeft: { x, y: y + height },
+ bottomRight: { x: x + width, y: y + height },
+ };
+}
+
+export function computePerspectiveMatrix(
+ srcCorners: PerspectiveCorners,
+ dstCorners: PerspectiveCorners
+): PerspectiveMatrix {
+ const src = [
+ srcCorners.topLeft,
+ srcCorners.topRight,
+ srcCorners.bottomRight,
+ srcCorners.bottomLeft,
+ ];
+
+ const dst = [
+ dstCorners.topLeft,
+ dstCorners.topRight,
+ dstCorners.bottomRight,
+ dstCorners.bottomLeft,
+ ];
+
+ const A: number[][] = [];
+ const B: number[] = [];
+
+ for (let i = 0; i < 4; i++) {
+ const sx = src[i].x;
+ const sy = src[i].y;
+ const dx = dst[i].x;
+ const dy = dst[i].y;
+
+ A.push([sx, sy, 1, 0, 0, 0, -dx * sx, -dx * sy]);
+ B.push(dx);
+
+ A.push([0, 0, 0, sx, sy, 1, -dy * sx, -dy * sy]);
+ B.push(dy);
+ }
+
+ const coeffs = solveLinearSystem(A, B);
+
+ if (!coeffs) {
+ return {
+ m00: 1, m01: 0, m02: 0,
+ m10: 0, m11: 1, m12: 0,
+ m20: 0, m21: 0, m22: 1,
+ };
+ }
+
+ return {
+ m00: coeffs[0],
+ m01: coeffs[1],
+ m02: coeffs[2],
+ m10: coeffs[3],
+ m11: coeffs[4],
+ m12: coeffs[5],
+ m20: coeffs[6],
+ m21: coeffs[7],
+ m22: 1,
+ };
+}
+
+function solveLinearSystem(A: number[][], B: number[]): number[] | null {
+ const n = B.length;
+ const augmented = A.map((row, i) => [...row, B[i]]);
+
+ for (let col = 0; col < n; col++) {
+ let maxRow = col;
+ for (let row = col + 1; row < n; row++) {
+ if (Math.abs(augmented[row][col]) > Math.abs(augmented[maxRow][col])) {
+ maxRow = row;
+ }
+ }
+
+ [augmented[col], augmented[maxRow]] = [augmented[maxRow], augmented[col]];
+
+ if (Math.abs(augmented[col][col]) < 1e-10) {
+ return null;
+ }
+
+ for (let row = col + 1; row < n; row++) {
+ const factor = augmented[row][col] / augmented[col][col];
+ for (let j = col; j <= n; j++) {
+ augmented[row][j] -= factor * augmented[col][j];
+ }
+ }
+ }
+
+ const x = new Array(n).fill(0);
+ for (let i = n - 1; i >= 0; i--) {
+ let sum = augmented[i][n];
+ for (let j = i + 1; j < n; j++) {
+ sum -= augmented[i][j] * x[j];
+ }
+ x[i] = sum / augmented[i][i];
+ }
+
+ return x;
+}
+
+export function transformPointPerspective(
+ x: number,
+ y: number,
+ matrix: PerspectiveMatrix
+): { x: number; y: number } {
+ const w = matrix.m20 * x + matrix.m21 * y + matrix.m22;
+
+ if (Math.abs(w) < 1e-10) {
+ return { x: 0, y: 0 };
+ }
+
+ return {
+ x: (matrix.m00 * x + matrix.m01 * y + matrix.m02) / w,
+ y: (matrix.m10 * x + matrix.m11 * y + matrix.m12) / w,
+ };
+}
+
+export function invertPerspectiveMatrix(matrix: PerspectiveMatrix): PerspectiveMatrix | null {
+ const { m00, m01, m02, m10, m11, m12, m20, m21, m22 } = matrix;
+
+ const det =
+ m00 * (m11 * m22 - m12 * m21) -
+ m01 * (m10 * m22 - m12 * m20) +
+ m02 * (m10 * m21 - m11 * m20);
+
+ if (Math.abs(det) < 1e-10) {
+ return null;
+ }
+
+ const invDet = 1 / det;
+
+ return {
+ m00: (m11 * m22 - m12 * m21) * invDet,
+ m01: (m02 * m21 - m01 * m22) * invDet,
+ m02: (m01 * m12 - m02 * m11) * invDet,
+ m10: (m12 * m20 - m10 * m22) * invDet,
+ m11: (m00 * m22 - m02 * m20) * invDet,
+ m12: (m02 * m10 - m00 * m12) * invDet,
+ m20: (m10 * m21 - m11 * m20) * invDet,
+ m21: (m01 * m20 - m00 * m21) * invDet,
+ m22: (m00 * m11 - m01 * m10) * invDet,
+ };
+}
+
+export function applyPerspectiveTransform(
+ imageData: ImageData,
+ srcCorners: PerspectiveCorners,
+ dstCorners: PerspectiveCorners,
+ outputWidth?: number,
+ outputHeight?: number,
+ interpolation: 'nearest' | 'bilinear' = 'bilinear'
+): ImageData {
+ const { width: srcWidth, height: srcHeight, data: srcData } = imageData;
+
+ const dstBounds = getDstBounds(dstCorners);
+ const dstWidth = outputWidth ?? Math.ceil(dstBounds.width);
+ const dstHeight = outputHeight ?? Math.ceil(dstBounds.height);
+ const dstData = new Uint8ClampedArray(dstWidth * dstHeight * 4);
+
+ const matrix = computePerspectiveMatrix(srcCorners, dstCorners);
+ const invMatrix = invertPerspectiveMatrix(matrix);
+
+ if (!invMatrix) {
+ return new ImageData(dstData, dstWidth, dstHeight);
+ }
+
+ for (let dstY = 0; dstY < dstHeight; dstY++) {
+ for (let dstX = 0; dstX < dstWidth; dstX++) {
+ const worldX = dstBounds.x + dstX;
+ const worldY = dstBounds.y + dstY;
+
+ const srcPoint = transformPointPerspective(worldX, worldY, invMatrix);
+
+ if (srcPoint.x < 0 || srcPoint.x >= srcWidth || srcPoint.y < 0 || srcPoint.y >= srcHeight) {
+ continue;
+ }
+
+ const dstIdx = (dstY * dstWidth + dstX) * 4;
+
+ if (interpolation === 'nearest') {
+ const srcX = Math.round(srcPoint.x);
+ const srcY = Math.round(srcPoint.y);
+ const srcIdx = (srcY * srcWidth + srcX) * 4;
+
+ dstData[dstIdx] = srcData[srcIdx];
+ dstData[dstIdx + 1] = srcData[srcIdx + 1];
+ dstData[dstIdx + 2] = srcData[srcIdx + 2];
+ dstData[dstIdx + 3] = srcData[srcIdx + 3];
+ } else {
+ const x0 = Math.floor(srcPoint.x);
+ const y0 = Math.floor(srcPoint.y);
+ const x1 = Math.min(x0 + 1, srcWidth - 1);
+ const y1 = Math.min(y0 + 1, srcHeight - 1);
+
+ const fx = srcPoint.x - x0;
+ const fy = srcPoint.y - y0;
+
+ const idx00 = (y0 * srcWidth + x0) * 4;
+ const idx10 = (y0 * srcWidth + x1) * 4;
+ const idx01 = (y1 * srcWidth + x0) * 4;
+ const idx11 = (y1 * srcWidth + x1) * 4;
+
+ for (let c = 0; c < 4; c++) {
+ const v00 = srcData[idx00 + c];
+ const v10 = srcData[idx10 + c];
+ const v01 = srcData[idx01 + c];
+ const v11 = srcData[idx11 + c];
+
+ const v =
+ v00 * (1 - fx) * (1 - fy) +
+ v10 * fx * (1 - fy) +
+ v01 * (1 - fx) * fy +
+ v11 * fx * fy;
+
+ dstData[dstIdx + c] = Math.round(v);
+ }
+ }
+ }
+ }
+
+ return new ImageData(dstData, dstWidth, dstHeight);
+}
+
+function getDstBounds(corners: PerspectiveCorners): { x: number; y: number; width: number; height: number } {
+ const xs = [corners.topLeft.x, corners.topRight.x, corners.bottomLeft.x, corners.bottomRight.x];
+ const ys = [corners.topLeft.y, corners.topRight.y, corners.bottomLeft.y, corners.bottomRight.y];
+
+ const minX = Math.min(...xs);
+ const maxX = Math.max(...xs);
+ const minY = Math.min(...ys);
+ const maxY = Math.max(...ys);
+
+ return {
+ x: minX,
+ y: minY,
+ width: maxX - minX,
+ height: maxY - minY,
+ };
+}
+
+export function renderPerspectiveBox(
+ ctx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D,
+ corners: PerspectiveCorners,
+ options: {
+ lineColor?: string;
+ handleColor?: string;
+ handleFillColor?: string;
+ handleSize?: number;
+ showGrid?: boolean;
+ gridDivisions?: number;
+ } = {}
+): void {
+ const {
+ lineColor = '#0ea5e9',
+ handleColor = '#0ea5e9',
+ handleFillColor = '#ffffff',
+ handleSize = 8,
+ showGrid = true,
+ gridDivisions = 3,
+ } = options;
+
+ ctx.save();
+
+ ctx.strokeStyle = lineColor;
+ ctx.lineWidth = 1.5;
+
+ ctx.beginPath();
+ ctx.moveTo(corners.topLeft.x, corners.topLeft.y);
+ ctx.lineTo(corners.topRight.x, corners.topRight.y);
+ ctx.lineTo(corners.bottomRight.x, corners.bottomRight.y);
+ ctx.lineTo(corners.bottomLeft.x, corners.bottomLeft.y);
+ ctx.closePath();
+ ctx.stroke();
+
+ if (showGrid) {
+ ctx.strokeStyle = lineColor;
+ ctx.lineWidth = 0.5;
+ ctx.setLineDash([4, 4]);
+
+ for (let i = 1; i < gridDivisions; i++) {
+ const t = i / gridDivisions;
+
+ const leftX = corners.topLeft.x + (corners.bottomLeft.x - corners.topLeft.x) * t;
+ const leftY = corners.topLeft.y + (corners.bottomLeft.y - corners.topLeft.y) * t;
+ const rightX = corners.topRight.x + (corners.bottomRight.x - corners.topRight.x) * t;
+ const rightY = corners.topRight.y + (corners.bottomRight.y - corners.topRight.y) * t;
+
+ ctx.beginPath();
+ ctx.moveTo(leftX, leftY);
+ ctx.lineTo(rightX, rightY);
+ ctx.stroke();
+
+ const topX = corners.topLeft.x + (corners.topRight.x - corners.topLeft.x) * t;
+ const topY = corners.topLeft.y + (corners.topRight.y - corners.topLeft.y) * t;
+ const bottomX = corners.bottomLeft.x + (corners.bottomRight.x - corners.bottomLeft.x) * t;
+ const bottomY = corners.bottomLeft.y + (corners.bottomRight.y - corners.bottomLeft.y) * t;
+
+ ctx.beginPath();
+ ctx.moveTo(topX, topY);
+ ctx.lineTo(bottomX, bottomY);
+ ctx.stroke();
+ }
+
+ ctx.setLineDash([]);
+ }
+
+ const cornerPoints = [corners.topLeft, corners.topRight, corners.bottomRight, corners.bottomLeft];
+
+ for (const corner of cornerPoints) {
+ ctx.beginPath();
+ ctx.fillStyle = handleFillColor;
+ ctx.strokeStyle = handleColor;
+ ctx.lineWidth = 1.5;
+ ctx.rect(
+ corner.x - handleSize / 2,
+ corner.y - handleSize / 2,
+ handleSize,
+ handleSize
+ );
+ ctx.fill();
+ ctx.stroke();
+ }
+
+ ctx.restore();
+}
+
+export function hitTestPerspectiveCorner(
+ x: number,
+ y: number,
+ corners: PerspectiveCorners,
+ threshold: number = 10
+): 'topLeft' | 'topRight' | 'bottomLeft' | 'bottomRight' | null {
+ const cornerMap: Array<{ key: keyof PerspectiveCorners; point: { x: number; y: number } }> = [
+ { key: 'topLeft', point: corners.topLeft },
+ { key: 'topRight', point: corners.topRight },
+ { key: 'bottomLeft', point: corners.bottomLeft },
+ { key: 'bottomRight', point: corners.bottomRight },
+ ];
+
+ for (const { key, point } of cornerMap) {
+ if (Math.hypot(x - point.x, y - point.y) <= threshold) {
+ return key;
+ }
+ }
+
+ return null;
+}
+
+export function moveCorner(
+ corners: PerspectiveCorners,
+ corner: keyof PerspectiveCorners,
+ dx: number,
+ dy: number
+): PerspectiveCorners {
+ return {
+ ...corners,
+ [corner]: {
+ x: corners[corner].x + dx,
+ y: corners[corner].y + dy,
+ },
+ };
+}
+
+export function isValidPerspective(corners: PerspectiveCorners): boolean {
+ const crossProduct = (
+ o: { x: number; y: number },
+ a: { x: number; y: number },
+ b: { x: number; y: number }
+ ) => (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x);
+
+ const points = [
+ corners.topLeft,
+ corners.topRight,
+ corners.bottomRight,
+ corners.bottomLeft,
+ ];
+
+ let sign = 0;
+ for (let i = 0; i < 4; i++) {
+ const o = points[i];
+ const a = points[(i + 1) % 4];
+ const b = points[(i + 2) % 4];
+ const cross = crossProduct(o, a, b);
+
+ if (cross !== 0) {
+ if (sign === 0) {
+ sign = Math.sign(cross);
+ } else if (Math.sign(cross) !== sign) {
+ return false;
+ }
+ }
+ }
+
+ return true;
+}
+
+export function constrainPerspective(
+ corners: PerspectiveCorners,
+ maxSkew: number = 0.8
+): PerspectiveCorners {
+ const centerX = (corners.topLeft.x + corners.topRight.x + corners.bottomLeft.x + corners.bottomRight.x) / 4;
+ const centerY = (corners.topLeft.y + corners.topRight.y + corners.bottomLeft.y + corners.bottomRight.y) / 4;
+
+ const constrain = (corner: { x: number; y: number }) => {
+ const dx = corner.x - centerX;
+ const dy = corner.y - centerY;
+ const dist = Math.hypot(dx, dy);
+ const maxDist = Math.max(Math.abs(dx), Math.abs(dy)) / maxSkew;
+
+ if (dist > maxDist && maxDist > 0) {
+ const scale = maxDist / dist;
+ return {
+ x: centerX + dx * scale,
+ y: centerY + dy * scale,
+ };
+ }
+
+ return corner;
+ };
+
+ return {
+ topLeft: constrain(corners.topLeft),
+ topRight: constrain(corners.topRight),
+ bottomLeft: constrain(corners.bottomLeft),
+ bottomRight: constrain(corners.bottomRight),
+ };
+}
diff --git a/apps/image/src/tools/transform/warp.ts b/apps/image/src/tools/transform/warp.ts
new file mode 100644
index 00000000..3c429c03
--- /dev/null
+++ b/apps/image/src/tools/transform/warp.ts
@@ -0,0 +1,602 @@
+export interface WarpGrid {
+ rows: number;
+ cols: number;
+ points: WarpPoint[][];
+}
+
+export interface WarpPoint {
+ x: number;
+ y: number;
+ handleLeft: { x: number; y: number } | null;
+ handleRight: { x: number; y: number } | null;
+ handleTop: { x: number; y: number } | null;
+ handleBottom: { x: number; y: number } | null;
+}
+
+export type WarpPreset =
+ | 'none'
+ | 'arc'
+ | 'arcLower'
+ | 'arcUpper'
+ | 'arch'
+ | 'bulge'
+ | 'shellLower'
+ | 'shellUpper'
+ | 'flag'
+ | 'wave'
+ | 'fish'
+ | 'rise'
+ | 'fisheye'
+ | 'inflate'
+ | 'squeeze'
+ | 'twist';
+
+export interface WarpSettings {
+ preset: WarpPreset;
+ bend: number;
+ horizontalDistortion: number;
+ verticalDistortion: number;
+ customGrid: WarpGrid | null;
+}
+
+export const DEFAULT_WARP_SETTINGS: WarpSettings = {
+ preset: 'none',
+ bend: 0,
+ horizontalDistortion: 0,
+ verticalDistortion: 0,
+ customGrid: null,
+};
+
+export function createWarpGrid(
+ width: number,
+ height: number,
+ rows: number = 4,
+ cols: number = 4
+): WarpGrid {
+ const points: WarpPoint[][] = [];
+
+ for (let row = 0; row <= rows; row++) {
+ const rowPoints: WarpPoint[] = [];
+ for (let col = 0; col <= cols; col++) {
+ const x = (col / cols) * width;
+ const y = (row / rows) * height;
+
+ const handleOffset = Math.min(width / cols, height / rows) * 0.3;
+
+ rowPoints.push({
+ x,
+ y,
+ handleLeft: col > 0 ? { x: x - handleOffset, y } : null,
+ handleRight: col < cols ? { x: x + handleOffset, y } : null,
+ handleTop: row > 0 ? { x, y: y - handleOffset } : null,
+ handleBottom: row < rows ? { x, y: y + handleOffset } : null,
+ });
+ }
+ points.push(rowPoints);
+ }
+
+ return { rows, cols, points };
+}
+
+export function applyWarpPreset(
+ grid: WarpGrid,
+ preset: WarpPreset,
+ bend: number,
+ hDistort: number,
+ vDistort: number
+): WarpGrid {
+ const { rows, cols, points } = grid;
+
+ const newPoints: WarpPoint[][] = points.map((row) =>
+ row.map((point) => ({ ...point }))
+ );
+
+ const centerX = points[0][cols].x / 2;
+ const centerY = points[rows][0].y / 2;
+ const width = points[0][cols].x;
+ const height = points[rows][0].y;
+
+ for (let row = 0; row <= rows; row++) {
+ for (let col = 0; col <= cols; col++) {
+ const point = newPoints[row][col];
+ const normalizedX = (point.x - centerX) / (width / 2);
+ const normalizedY = (point.y - centerY) / (height / 2);
+
+ let dx = 0;
+ let dy = 0;
+
+ switch (preset) {
+ case 'arc': {
+ const factor = bend / 100;
+ dy = -factor * height * 0.3 * (1 - normalizedX * normalizedX);
+ break;
+ }
+
+ case 'arcLower': {
+ const factor = bend / 100;
+ if (normalizedY > 0) {
+ dy = factor * height * 0.3 * (1 - normalizedX * normalizedX) * normalizedY;
+ }
+ break;
+ }
+
+ case 'arcUpper': {
+ const factor = bend / 100;
+ if (normalizedY < 0) {
+ dy = -factor * height * 0.3 * (1 - normalizedX * normalizedX) * Math.abs(normalizedY);
+ }
+ break;
+ }
+
+ case 'arch': {
+ const factor = bend / 100;
+ const archY = (1 - Math.pow(normalizedX, 2)) * factor * height * 0.3;
+ dy = normalizedY < 0 ? -archY : 0;
+ dx = normalizedX * factor * width * 0.1 * (1 - Math.abs(normalizedY));
+ break;
+ }
+
+ case 'bulge': {
+ const factor = bend / 100;
+ const dist = Math.sqrt(normalizedX * normalizedX + normalizedY * normalizedY);
+ const bulge = Math.max(0, 1 - dist) * factor;
+ dx = normalizedX * bulge * width * 0.2;
+ dy = normalizedY * bulge * height * 0.2;
+ break;
+ }
+
+ case 'shellLower': {
+ const factor = bend / 100;
+ if (normalizedY > 0) {
+ dx = normalizedX * factor * width * 0.1 * normalizedY;
+ }
+ break;
+ }
+
+ case 'shellUpper': {
+ const factor = bend / 100;
+ if (normalizedY < 0) {
+ dx = normalizedX * factor * width * 0.1 * Math.abs(normalizedY);
+ }
+ break;
+ }
+
+ case 'flag': {
+ const factor = bend / 100;
+ dy = Math.sin(normalizedX * Math.PI * 2) * factor * height * 0.15;
+ break;
+ }
+
+ case 'wave': {
+ const factor = bend / 100;
+ dy = Math.sin(normalizedX * Math.PI * 3) * factor * height * 0.1;
+ dx = Math.sin(normalizedY * Math.PI * 3) * factor * width * 0.05;
+ break;
+ }
+
+ case 'fish': {
+ const factor = bend / 100;
+ const fishFactor = Math.pow(Math.abs(normalizedY), 2);
+ dx = normalizedX * fishFactor * factor * width * 0.3;
+ break;
+ }
+
+ case 'rise': {
+ const factor = bend / 100;
+ dy = normalizedX * normalizedX * factor * height * 0.2 * (normalizedY + 1);
+ break;
+ }
+
+ case 'fisheye': {
+ const factor = bend / 100;
+ const dist = Math.sqrt(normalizedX * normalizedX + normalizedY * normalizedY);
+ const fisheyeFactor = Math.pow(dist, 2) * factor;
+ dx = normalizedX * fisheyeFactor * width * 0.2;
+ dy = normalizedY * fisheyeFactor * height * 0.2;
+ break;
+ }
+
+ case 'inflate': {
+ const factor = bend / 100;
+ const dist = Math.sqrt(normalizedX * normalizedX + normalizedY * normalizedY);
+ const inflate = (1 - dist * dist) * factor;
+ dx = normalizedX * inflate * width * 0.15;
+ dy = normalizedY * inflate * height * 0.15;
+ break;
+ }
+
+ case 'squeeze': {
+ const factor = bend / 100;
+ const squeeze = Math.abs(normalizedY) * factor;
+ dx = -normalizedX * squeeze * width * 0.2;
+ break;
+ }
+
+ case 'twist': {
+ const factor = (bend / 100) * Math.PI * 0.5;
+ const dist = Math.sqrt(normalizedX * normalizedX + normalizedY * normalizedY);
+ const angle = dist * factor;
+ const cos = Math.cos(angle);
+ const sin = Math.sin(angle);
+ const newX = normalizedX * cos - normalizedY * sin;
+ const newY = normalizedX * sin + normalizedY * cos;
+ dx = (newX - normalizedX) * width * 0.4;
+ dy = (newY - normalizedY) * height * 0.4;
+ break;
+ }
+ }
+
+ dx += normalizedY * hDistort * width * 0.002;
+ dy += normalizedX * vDistort * height * 0.002;
+
+ point.x += dx;
+ point.y += dy;
+
+ if (point.handleLeft) {
+ point.handleLeft.x += dx;
+ point.handleLeft.y += dy;
+ }
+ if (point.handleRight) {
+ point.handleRight.x += dx;
+ point.handleRight.y += dy;
+ }
+ if (point.handleTop) {
+ point.handleTop.x += dx;
+ point.handleTop.y += dy;
+ }
+ if (point.handleBottom) {
+ point.handleBottom.x += dx;
+ point.handleBottom.y += dy;
+ }
+ }
+ }
+
+ return { rows, cols, points: newPoints };
+}
+
+function cubicBezier(
+ p0: number,
+ p1: number,
+ p2: number,
+ p3: number,
+ t: number
+): number {
+ const mt = 1 - t;
+ return mt * mt * mt * p0 + 3 * mt * mt * t * p1 + 3 * mt * t * t * p2 + t * t * t * p3;
+}
+
+function bicubicInterpolate(
+ grid: WarpGrid,
+ u: number,
+ v: number
+): { x: number; y: number } {
+ const { rows, cols, points } = grid;
+
+ const colF = u * cols;
+ const rowF = v * rows;
+
+ const col = Math.min(Math.floor(colF), cols - 1);
+ const row = Math.min(Math.floor(rowF), rows - 1);
+
+ const localU = colF - col;
+ const localV = rowF - row;
+
+ const p00 = points[row][col];
+ const p01 = points[row][col + 1];
+ const p10 = points[row + 1][col];
+ const p11 = points[row + 1][col + 1];
+
+ const topX = cubicBezier(
+ p00.x,
+ p00.handleRight?.x ?? p00.x,
+ p01.handleLeft?.x ?? p01.x,
+ p01.x,
+ localU
+ );
+ const topY = cubicBezier(
+ p00.y,
+ p00.handleRight?.y ?? p00.y,
+ p01.handleLeft?.y ?? p01.y,
+ p01.y,
+ localU
+ );
+
+ const bottomX = cubicBezier(
+ p10.x,
+ p10.handleRight?.x ?? p10.x,
+ p11.handleLeft?.x ?? p11.x,
+ p11.x,
+ localU
+ );
+ const bottomY = cubicBezier(
+ p10.y,
+ p10.handleRight?.y ?? p10.y,
+ p11.handleLeft?.y ?? p11.y,
+ p11.y,
+ localU
+ );
+
+ const leftX = cubicBezier(
+ p00.x,
+ p00.handleBottom?.x ?? p00.x,
+ p10.handleTop?.x ?? p10.x,
+ p10.x,
+ localV
+ );
+ const leftY = cubicBezier(
+ p00.y,
+ p00.handleBottom?.y ?? p00.y,
+ p10.handleTop?.y ?? p10.y,
+ p10.y,
+ localV
+ );
+
+ const rightX = cubicBezier(
+ p01.x,
+ p01.handleBottom?.x ?? p01.x,
+ p11.handleTop?.x ?? p11.x,
+ p11.x,
+ localV
+ );
+ const rightY = cubicBezier(
+ p01.y,
+ p01.handleBottom?.y ?? p01.y,
+ p11.handleTop?.y ?? p11.y,
+ p11.y,
+ localV
+ );
+
+ const x = (topX + bottomX + leftX + rightX) / 4 +
+ (localU - 0.5) * (rightX - leftX) / 2 +
+ (localV - 0.5) * (bottomX - topX) / 2;
+
+ const y = (topY + bottomY + leftY + rightY) / 4 +
+ (localU - 0.5) * (rightY - leftY) / 2 +
+ (localV - 0.5) * (bottomY - topY) / 2;
+
+ return { x, y };
+}
+
+export function applyWarp(
+ imageData: ImageData,
+ grid: WarpGrid,
+ interpolation: 'nearest' | 'bilinear' = 'bilinear'
+): ImageData {
+ const { width, height, data } = imageData;
+ const resultData = new Uint8ClampedArray(data.length);
+
+ for (let y = 0; y < height; y++) {
+ for (let x = 0; x < width; x++) {
+ const u = x / width;
+ const v = y / height;
+
+ const warped = bicubicInterpolate(grid, u, v);
+
+ const srcX = warped.x;
+ const srcY = warped.y;
+
+ if (srcX < 0 || srcX >= width || srcY < 0 || srcY >= height) {
+ continue;
+ }
+
+ const dstIdx = (y * width + x) * 4;
+
+ if (interpolation === 'nearest') {
+ const sx = Math.round(srcX);
+ const sy = Math.round(srcY);
+ const srcIdx = (sy * width + sx) * 4;
+
+ resultData[dstIdx] = data[srcIdx];
+ resultData[dstIdx + 1] = data[srcIdx + 1];
+ resultData[dstIdx + 2] = data[srcIdx + 2];
+ resultData[dstIdx + 3] = data[srcIdx + 3];
+ } else {
+ const x0 = Math.floor(srcX);
+ const y0 = Math.floor(srcY);
+ const x1 = Math.min(x0 + 1, width - 1);
+ const y1 = Math.min(y0 + 1, height - 1);
+
+ const fx = srcX - x0;
+ const fy = srcY - y0;
+
+ const idx00 = (y0 * width + x0) * 4;
+ const idx10 = (y0 * width + x1) * 4;
+ const idx01 = (y1 * width + x0) * 4;
+ const idx11 = (y1 * width + x1) * 4;
+
+ for (let c = 0; c < 4; c++) {
+ const v00 = data[idx00 + c];
+ const v10 = data[idx10 + c];
+ const v01 = data[idx01 + c];
+ const v11 = data[idx11 + c];
+
+ const interpolatedValue =
+ v00 * (1 - fx) * (1 - fy) +
+ v10 * fx * (1 - fy) +
+ v01 * (1 - fx) * fy +
+ v11 * fx * fy;
+
+ resultData[dstIdx + c] = Math.round(interpolatedValue);
+ }
+ }
+ }
+ }
+
+ return new ImageData(resultData, width, height);
+}
+
+export function renderWarpGrid(
+ ctx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D,
+ grid: WarpGrid,
+ options: {
+ gridColor?: string;
+ pointColor?: string;
+ handleColor?: string;
+ pointSize?: number;
+ handleSize?: number;
+ showHandles?: boolean;
+ } = {}
+): void {
+ const {
+ gridColor = '#0ea5e9',
+ pointColor = '#ffffff',
+ handleColor = '#0ea5e9',
+ pointSize = 6,
+ handleSize = 4,
+ showHandles = true,
+ } = options;
+
+ const { rows, cols, points } = grid;
+
+ ctx.save();
+
+ ctx.strokeStyle = gridColor;
+ ctx.lineWidth = 1;
+
+ for (let row = 0; row <= rows; row++) {
+ ctx.beginPath();
+ for (let col = 0; col <= cols; col++) {
+ const point = points[row][col];
+ if (col === 0) {
+ ctx.moveTo(point.x, point.y);
+ } else {
+ const prevPoint = points[row][col - 1];
+ const cp1 = prevPoint.handleRight || prevPoint;
+ const cp2 = point.handleLeft || point;
+ ctx.bezierCurveTo(cp1.x, cp1.y, cp2.x, cp2.y, point.x, point.y);
+ }
+ }
+ ctx.stroke();
+ }
+
+ for (let col = 0; col <= cols; col++) {
+ ctx.beginPath();
+ for (let row = 0; row <= rows; row++) {
+ const point = points[row][col];
+ if (row === 0) {
+ ctx.moveTo(point.x, point.y);
+ } else {
+ const prevPoint = points[row - 1][col];
+ const cp1 = prevPoint.handleBottom || prevPoint;
+ const cp2 = point.handleTop || point;
+ ctx.bezierCurveTo(cp1.x, cp1.y, cp2.x, cp2.y, point.x, point.y);
+ }
+ }
+ ctx.stroke();
+ }
+
+ for (let row = 0; row <= rows; row++) {
+ for (let col = 0; col <= cols; col++) {
+ const point = points[row][col];
+
+ if (showHandles) {
+ ctx.strokeStyle = handleColor;
+ ctx.lineWidth = 1;
+
+ const handles = [point.handleLeft, point.handleRight, point.handleTop, point.handleBottom];
+ for (const handle of handles) {
+ if (handle) {
+ ctx.beginPath();
+ ctx.moveTo(point.x, point.y);
+ ctx.lineTo(handle.x, handle.y);
+ ctx.stroke();
+
+ ctx.beginPath();
+ ctx.fillStyle = handleColor;
+ ctx.arc(handle.x, handle.y, handleSize / 2, 0, Math.PI * 2);
+ ctx.fill();
+ }
+ }
+ }
+
+ ctx.beginPath();
+ ctx.fillStyle = pointColor;
+ ctx.strokeStyle = handleColor;
+ ctx.lineWidth = 1.5;
+ ctx.arc(point.x, point.y, pointSize / 2, 0, Math.PI * 2);
+ ctx.fill();
+ ctx.stroke();
+ }
+ }
+
+ ctx.restore();
+}
+
+export function hitTestWarpGrid(
+ grid: WarpGrid,
+ x: number,
+ y: number,
+ threshold: number = 8
+): { row: number; col: number; handleType: 'point' | 'left' | 'right' | 'top' | 'bottom' } | null {
+ const { rows, cols, points } = grid;
+
+ for (let row = 0; row <= rows; row++) {
+ for (let col = 0; col <= cols; col++) {
+ const point = points[row][col];
+
+ if (Math.hypot(x - point.x, y - point.y) <= threshold) {
+ return { row, col, handleType: 'point' };
+ }
+
+ if (point.handleLeft && Math.hypot(x - point.handleLeft.x, y - point.handleLeft.y) <= threshold) {
+ return { row, col, handleType: 'left' };
+ }
+ if (point.handleRight && Math.hypot(x - point.handleRight.x, y - point.handleRight.y) <= threshold) {
+ return { row, col, handleType: 'right' };
+ }
+ if (point.handleTop && Math.hypot(x - point.handleTop.x, y - point.handleTop.y) <= threshold) {
+ return { row, col, handleType: 'top' };
+ }
+ if (point.handleBottom && Math.hypot(x - point.handleBottom.x, y - point.handleBottom.y) <= threshold) {
+ return { row, col, handleType: 'bottom' };
+ }
+ }
+ }
+
+ return null;
+}
+
+export function moveWarpPoint(
+ grid: WarpGrid,
+ row: number,
+ col: number,
+ handleType: 'point' | 'left' | 'right' | 'top' | 'bottom',
+ dx: number,
+ dy: number
+): WarpGrid {
+ const newPoints = grid.points.map((r) => r.map((p) => ({ ...p })));
+ const point = newPoints[row][col];
+
+ if (handleType === 'point') {
+ point.x += dx;
+ point.y += dy;
+
+ if (point.handleLeft) {
+ point.handleLeft = { x: point.handleLeft.x + dx, y: point.handleLeft.y + dy };
+ }
+ if (point.handleRight) {
+ point.handleRight = { x: point.handleRight.x + dx, y: point.handleRight.y + dy };
+ }
+ if (point.handleTop) {
+ point.handleTop = { x: point.handleTop.x + dx, y: point.handleTop.y + dy };
+ }
+ if (point.handleBottom) {
+ point.handleBottom = { x: point.handleBottom.x + dx, y: point.handleBottom.y + dy };
+ }
+ } else {
+ const handleMap = {
+ left: 'handleLeft',
+ right: 'handleRight',
+ top: 'handleTop',
+ bottom: 'handleBottom',
+ } as const;
+
+ const handle = point[handleMap[handleType]];
+ if (handle) {
+ handle.x += dx;
+ handle.y += dy;
+ }
+ }
+
+ return { ...grid, points: newPoints };
+}