A lightweight Clip Studio Paint alternative with real-time multiplayer collaborative drawing. Built with Tauri and React.
TypeScript animationcartoonclip-studio-paintcollaborativedesktop-appdigital-paintingdrawing-appillustrationmangamultiplayeropen-sourcerusttaurithreejswebglwebtoon
import { HistoryActionType, TileDelta, VectorStroke } from '../types/editor';
import {
BYTES_1BIT,
BYTES_8BIT,
BYTES_32BIT,
TILE_PIXELS,
TileFormat,
getTileByteSize,
} from './tauriEnv';
/**
* Spatial/neighborhood raster operations whose partial pixel-level inversion around
* an overlapping peer stroke would create torn seams or distorted artifacts.
*/
export const NON_INVERTIBLE_COLLAB_UNDO_ACTIONS: ReadonlySet<HistoryActionType> = new Set<HistoryActionType>([
'liquify',
'filter',
'retouch',
'tonal-correction',
'canvas-resize',
]);
export function isNonInvertibleCollabAction(actionType?: HistoryActionType): boolean {
return actionType !== undefined && NON_INVERTIBLE_COLLAB_UNDO_ACTIONS.has(actionType);
}
function isAllZeroBytes(buf: Uint8Array): boolean {
if (buf.byteLength % 4 === 0 && buf.byteOffset % 4 === 0) {
const u32 = new Uint32Array(buf.buffer, buf.byteOffset, buf.byteLength >>> 2);
for (let i = 0; i < u32.length; i++) {
if (u32[i] !== 0) return false;
}
return true;
}
for (let i = 0; i < buf.byteLength; i++) {
if (buf[i] !== 0) return false;
}
return true;
}
/**
* Fast equality check between two tile buffers where `null`/`undefined` is equivalent to all-zero bytes.
*/
export function tileBytesEqual(
a: Uint8Array | null | undefined,
b: Uint8Array | null | undefined
): boolean {
const bufA = a ?? null;
const bufB = b ?? null;
if (bufA === bufB) return true;
if (bufA === null) return isAllZeroBytes(bufB!);
if (bufB === null) return isAllZeroBytes(bufA);
if (bufA.byteLength !== bufB.byteLength) return false;
if (
bufA.byteLength % 4 === 0 &&
bufA.byteOffset % 4 === 0 &&
bufB.byteOffset % 4 === 0
) {
const len32 = bufA.byteLength >>> 2;
const a32 = new Uint32Array(bufA.buffer, bufA.byteOffset, len32);
const b32 = new Uint32Array(bufB.buffer, bufB.byteOffset, len32);
for (let i = 0; i < len32; i++) {
if (a32[i] !== b32[i]) return false;
}
return true;
}
for (let i = 0; i < bufA.byteLength; i++) {
if (bufA[i] !== bufB[i]) return false;
}
return true;
}
function popcount8(n: number): number {
let x = n & 0xff;
x = x - ((x >> 1) & 0x55);
x = (x & 0x33) + ((x >> 2) & 0x33);
return (x + (x >> 4)) & 0x0f;
}
export interface ResolvedContestedTile {
action: 'replace' | 'delete' | 'skip';
nextData: Uint8Array | null;
appliedPixels: number;
overlappedPixels: number;
skippedNonInvertible: boolean;
}
/**
* Computes a conflict-safe tile state when another peer modified the same 256x256 tile
* after a local history step was recorded.
*
* - Pixels not touched by our local step (`source === target`) always keep `current`.
* - Pixels touched by our local step and untouched since (`current === source`) cleanly transition to `target`.
* - Pixels modified by another peer after our step (`current !== source`) preserve the peer's newer pixels.
* - For non-invertible neighborhood ops (`liquify`, `filter`, `retouch`, `tonal-correction`) with any
* overlapping remote pixel on the tile, the entire contested tile is preserved cleanly without tearing.
*/
export function resolveContestedTileDelta(
delta: Pick<TileDelta, 'format' | 'beforeData' | 'afterData'>,
currentData: Uint8Array | null,
currentFormat: TileFormat | null,
direction: 'undo' | 'redo',
isNonInvertible: boolean
): ResolvedContestedTile {
if (currentFormat !== null && currentFormat !== delta.format) {
return {
action: 'skip',
nextData: currentData,
appliedPixels: 0,
overlappedPixels: 1,
skippedNonInvertible: true,
};
}
const expectedLen = getTileByteSize(delta.format);
const sourceData = direction === 'undo' ? delta.afterData ?? null : delta.beforeData ?? null;
const targetData = direction === 'undo' ? delta.beforeData ?? null : delta.afterData ?? null;
if (
(sourceData !== null && sourceData.byteLength !== expectedLen) ||
(targetData !== null && targetData.byteLength !== expectedLen) ||
(currentData !== null && currentData.byteLength !== expectedLen)
) {
return {
action: 'skip',
nextData: currentData,
appliedPixels: 0,
overlappedPixels: 1,
skippedNonInvertible: true,
};
}
let appliedPixels = 0;
let overlappedPixels = 0;
let anyNonZero = 0;
if (delta.format === 'color-32bit') {
const out = new Uint8Array(BYTES_32BIT);
const out32 = new Uint32Array(out.buffer);
const src32 =
sourceData && sourceData.byteOffset % 4 === 0
? new Uint32Array(sourceData.buffer, sourceData.byteOffset, TILE_PIXELS)
: null;
const tgt32 =
targetData && targetData.byteOffset % 4 === 0
? new Uint32Array(targetData.buffer, targetData.byteOffset, TILE_PIXELS)
: null;
const cur32 =
currentData && currentData.byteOffset % 4 === 0
? new Uint32Array(currentData.buffer, currentData.byteOffset, TILE_PIXELS)
: null;
const readU32 = (u32: Uint32Array | null, raw: Uint8Array | null, idx: number): number => {
if (u32 !== null) return u32[idx];
if (raw === null) return 0;
const o = idx << 2;
return (raw[o] | (raw[o + 1] << 8) | (raw[o + 2] << 16) | (raw[o + 3] << 24)) >>> 0;
};
for (let i = 0; i < TILE_PIXELS; i++) {
const s = readU32(src32, sourceData, i);
const t = readU32(tgt32, targetData, i);
const c = readU32(cur32, currentData, i);
if (s === t) {
out32[i] = c;
} else if (c === s) {
out32[i] = t;
appliedPixels++;
} else {
out32[i] = c;
overlappedPixels++;
}
anyNonZero |= out32[i];
}
if (isNonInvertible && overlappedPixels > 0) {
return {
action: 'skip',
nextData: currentData,
appliedPixels: 0,
overlappedPixels,
skippedNonInvertible: true,
};
}
if (appliedPixels === 0) {
return {
action: 'skip',
nextData: currentData,
appliedPixels: 0,
overlappedPixels,
skippedNonInvertible: false,
};
}
if (anyNonZero === 0) {
return {
action: 'delete',
nextData: null,
appliedPixels,
overlappedPixels,
skippedNonInvertible: false,
};
}
return {
action: 'replace',
nextData: out,
appliedPixels,
overlappedPixels,
skippedNonInvertible: false,
};
}
if (delta.format === 'grayscale-8bit') {
const out = new Uint8Array(BYTES_8BIT);
for (let i = 0; i < BYTES_8BIT; i++) {
const s = sourceData ? sourceData[i] : 0;
const t = targetData ? targetData[i] : 0;
const c = currentData ? currentData[i] : 0;
if (s === t) {
out[i] = c;
} else if (c === s) {
out[i] = t;
appliedPixels++;
} else {
out[i] = c;
overlappedPixels++;
}
anyNonZero |= out[i];
}
if (isNonInvertible && overlappedPixels > 0) {
return {
action: 'skip',
nextData: currentData,
appliedPixels: 0,
overlappedPixels,
skippedNonInvertible: true,
};
}
if (appliedPixels === 0) {
return {
action: 'skip',
nextData: currentData,
appliedPixels: 0,
overlappedPixels,
skippedNonInvertible: false,
};
}
if (anyNonZero === 0) {
return {
action: 'delete',
nextData: null,
appliedPixels,
overlappedPixels,
skippedNonInvertible: false,
};
}
return {
action: 'replace',
nextData: out,
appliedPixels,
overlappedPixels,
skippedNonInvertible: false,
};
}
// monochrome-1bit: 8 pixels packed per byte
const out = new Uint8Array(BYTES_1BIT);
for (let i = 0; i < BYTES_1BIT; i++) {
const s = sourceData ? sourceData[i] : 0;
const t = targetData ? targetData[i] : 0;
const c = currentData ? currentData[i] : 0;
const localChanged = (s ^ t) & 0xff;
const unoverwritten = ~(c ^ s) & 0xff;
const applyMask = localChanged & unoverwritten;
const overlapMask = localChanged & (~unoverwritten & 0xff);
out[i] = (c & (~applyMask & 0xff)) | (t & applyMask);
if (applyMask !== 0) appliedPixels += popcount8(applyMask);
if (overlapMask !== 0) overlappedPixels += popcount8(overlapMask);
anyNonZero |= out[i];
}
if (isNonInvertible && overlappedPixels > 0) {
return {
action: 'skip',
nextData: currentData,
appliedPixels: 0,
overlappedPixels,
skippedNonInvertible: true,
};
}
if (appliedPixels === 0) {
return {
action: 'skip',
nextData: currentData,
appliedPixels: 0,
overlappedPixels,
skippedNonInvertible: false,
};
}
if (anyNonZero === 0) {
return {
action: 'delete',
nextData: null,
appliedPixels,
overlappedPixels,
skippedNonInvertible: false,
};
}
return {
action: 'replace',
nextData: out,
appliedPixels,
overlappedPixels,
skippedNonInvertible: false,
};
}
export interface SelectiveVectorApplyResult {
nextStrokes: VectorStroke[];
changed: boolean;
broadcastMode: 'selective-undo' | 'layer-update' | 'none';
selectiveUndoStrokeId?: string;
}
/**
* Marks a single vector stroke as tombstoned (`deleted: true`) without affecting
* any other peer's strokes on the same vector layer.
*/
export function markVectorStrokeDeleted(
currentStrokes: VectorStroke[],
strokeId: string
): { nextStrokes: VectorStroke[]; changed: boolean } {
let changed = false;
const nextStrokes = currentStrokes.map((st) => {
if (st.id !== strokeId) return st;
if (st.deleted) return st;
changed = true;
return { ...st, deleted: true };
});
return { nextStrokes: changed ? nextStrokes : currentStrokes, changed };
}
/**
* Applies collaborative selective undo/redo on a vector layer without overwriting
* strokes created concurrently by other peers.
*/
export function applySelectiveVectorStep(
currentStrokes: VectorStroke[],
delta: { before: VectorStroke[]; after: VectorStroke[] },
direction: 'undo' | 'redo',
targetStrokeId?: string
): SelectiveVectorApplyResult {
const beforeById = new Map<string, VectorStroke>();
for (let i = 0; i < delta.before.length; i++) {
beforeById.set(delta.before[i].id, delta.before[i]);
}
const afterById = new Map<string, VectorStroke>();
const addedStrokes: VectorStroke[] = [];
for (let i = 0; i < delta.after.length; i++) {
const st = delta.after[i];
afterById.set(st.id, st);
if (!beforeById.has(st.id)) {
addedStrokes.push(st);
}
}
// Detect pure stroke-addition steps (no pre-existing strokes removed or modified)
let modifiedOrRemovedBefore = false;
for (let i = 0; i < delta.before.length; i++) {
const b = delta.before[i];
const a = afterById.get(b.id);
if (!a || a !== b) {
if (
!a ||
Boolean(a.deleted) !== Boolean(b.deleted) ||
a.knots.length !== b.knots.length ||
a.color !== b.color ||
a.baseWidth !== b.baseWidth ||
a.opacity !== b.opacity
) {
modifiedOrRemovedBefore = true;
break;
}
}
}
if (!modifiedOrRemovedBefore && addedStrokes.length > 0) {
const addedIds = new Set(addedStrokes.map((s) => s.id));
if (direction === 'undo') {
let changed = false;
const nextStrokes = currentStrokes.map((st) => {
if (!addedIds.has(st.id)) return st;
if (st.deleted) return st;
changed = true;
return { ...st, deleted: true };
});
const singleId =
addedStrokes.length === 1
? addedStrokes[0].id
: targetStrokeId && addedIds.has(targetStrokeId)
? targetStrokeId
: undefined;
return {
nextStrokes: changed ? nextStrokes : currentStrokes,
changed,
broadcastMode: changed
? singleId && addedStrokes.length === 1
? 'selective-undo'
: 'layer-update'
: 'none',
selectiveUndoStrokeId: singleId,
};
}
// Redo of stroke addition: un-tombstone existing entries or re-append missing ones
const existingIds = new Set<string>();
let changed = false;
const nextStrokes = currentStrokes.map((st) => {
existingIds.add(st.id);
if (!addedIds.has(st.id)) return st;
if (!st.deleted) return st;
changed = true;
const { deleted: _deleted, ...rest } = st;
return rest as VectorStroke;
});
for (let i = 0; i < addedStrokes.length; i++) {
const added = addedStrokes[i];
if (!existingIds.has(added.id)) {
const { deleted: _deleted, ...rest } = added;
nextStrokes.push(rest as VectorStroke);
changed = true;
}
}
return {
nextStrokes: changed ? nextStrokes : currentStrokes,
changed,
broadcastMode: changed ? 'layer-update' : 'none',
};
}
// Fallback for targeted strokeId when delta was non-additive or simplified
if (direction === 'undo' && targetStrokeId && currentStrokes.some((s) => s.id === targetStrokeId)) {
const res = markVectorStrokeDeleted(currentStrokes, targetStrokeId);
if (res.changed) {
return {
nextStrokes: res.nextStrokes,
changed: true,
broadcastMode: 'selective-undo',
selectiveUndoStrokeId: targetStrokeId,
};
}
}
// Non-additive vector edit (e.g. vector eraser, pinch, width edit): preserve any strokes added concurrently by peers
const knownIds = new Set<string>([...beforeById.keys(), ...afterById.keys()]);
const concurrentPeerStrokes = currentStrokes.filter((st) => !knownIds.has(st.id));
const baseTarget = direction === 'undo' ? delta.before : delta.after;
const nextStrokes =
concurrentPeerStrokes.length > 0
? [...baseTarget, ...concurrentPeerStrokes]
: [...baseTarget];
return {
nextStrokes,
changed: true,
broadcastMode: 'layer-update',
};
}