aboutsummaryrefslogtreecommitdiff
path: root/src/client/util/bezierFit.ts
diff options
context:
space:
mode:
Diffstat (limited to 'src/client/util/bezierFit.ts')
-rw-r--r--src/client/util/bezierFit.ts253
1 files changed, 194 insertions, 59 deletions
diff --git a/src/client/util/bezierFit.ts b/src/client/util/bezierFit.ts
index 4aef28e6b..0399fe1d5 100644
--- a/src/client/util/bezierFit.ts
+++ b/src/client/util/bezierFit.ts
@@ -1,8 +1,7 @@
/* eslint-disable no-use-before-define */
-/* eslint-disable prefer-destructuring */
/* eslint-disable no-param-reassign */
-/* eslint-disable camelcase */
import { Point } from '../../pen-gestures/ndollar';
+import { numberRange } from '../../Utils';
export enum SVGType {
Rect = 'rect',
@@ -625,13 +624,132 @@ export function GenerateControlPoints(coordinates: Point[], alpha = 0.1) {
return [...firstEnd, ...points, ...lastEnd];
}
-export function SVGToBezier(name: SVGType, attributes: any): Point[] {
+function convertRelativePathCmdsToAbsolute(pathData: string): string {
+ const commands = pathData.match(/[a-zA-Z][^a-zA-Z]*/g);
+ let currentX = 0;
+ let currentY = 0;
+ let startX = 0;
+ let startY = 0;
+ const absoluteCommands = commands?.map(command => {
+ const values = command
+ .slice(1)
+ .trim()
+ .split(/[\s,]+/)
+ .map(v => +v);
+
+ switch (command[0]) {
+ case 'M':
+ currentX = values[0];
+ currentY = values[1];
+ startX = currentX;
+ startY = currentY;
+ return `M${currentX},${currentY}`;
+ case 'm':
+ currentX += values[0];
+ currentY += values[1];
+ startX = currentX;
+ startY = currentY;
+ return `M${currentX},${currentY}`;
+ case 'L':
+ currentX = values[values.length - 2];
+ currentY = values[values.length - 1];
+ return `L${values.join(',')}`;
+ case 'l': {
+ let str = '';
+ for (let i = 0; i < values.length; i += 2) {
+ str += (i === 0 ? 'L':',') + (values[i] + currentX) +
+ ',' + (values[i + 1] + currentY); // prettier-ignore
+ currentX += values[i];
+ currentY += values[i + 1];
+ }
+ return str;
+ }
+ case 'H':
+ currentX = values[0];
+ return `H${currentX}`;
+ case 'h':
+ currentX += values[0];
+ return `H${currentX}`;
+ case 'V':
+ currentY = values[0];
+ return `V${currentY}`;
+ case 'v':
+ currentY += values[0];
+ return `V${currentY}`;
+ case 'C':
+ currentX = values[values.length - 2];
+ currentY = values[values.length - 1];
+ return `C${values.join(',')}`;
+ case 'c': {
+ let str = '';
+ for (let i = 0; i < values.length; i += 6) {
+ str += (i === 0 ? 'C':',') + (values[i] + currentX) +
+ ',' + (values[i + 1] + currentY) +
+ ',' + (values[i + 2] + currentX) +
+ ',' + (values[i + 3] + currentY) +
+ ',' + (values[i + 4] + currentX) +
+ ',' + (values[i + 5] + currentY); // prettier-ignore
+ currentX += values[i + 4];
+ currentY += values[i + 5];
+ }
+ return str;
+ }
+ case 'S':
+ currentX = values[2];
+ currentY = values[3];
+ return `S${values.join(',')}`;
+ case 's':
+ return `S${values.map((v, i) => (i % 2 === 0 ? (currentX += v) : (currentY += v))).join(',')}`;
+ case 'Q':
+ currentX = values[values.length - 2];
+ currentY = values[values.length - 1];
+ return `Q${values.join(',')}`;
+ case 'q': {
+ let str = '';
+ for (let i = 0; i < values.length; i += 4) {
+ str += (i === 0 ? 'Q':',') + (values[i] + currentX) +
+ ',' + (values[i + 1] + currentY) +
+ ',' + (values[i + 2] + currentX) +
+ ',' + (values[i + 3] + currentY); // prettier-ignore
+ currentX += values[i + 2];
+ currentY += values[i + 3];
+ }
+ return str;
+ }
+ case 'T':
+ currentX = values[0];
+ currentY = values[1];
+ return `T${currentX},${currentY}`;
+ case 't':
+ currentX += values[0];
+ currentY += values[1];
+ return `T${currentX},${currentY}`;
+ case 'A':
+ currentX = values[5];
+ currentY = values[6];
+ return `A${values.join(',')}`;
+ case 'a':
+ return `A${values.map((v, i) => (i % 2 === 0 ? (currentX += v) : (currentY += v))).join(',')}`;
+ case 'Z':
+ case 'z':
+ currentX = startX;
+ currentY = startY;
+ return 'Z';
+ default:
+ return command;
+ }
+ });
+
+ return absoluteCommands?.join(' ') ?? pathData;
+}
+
+export function SVGToBezier(name: SVGType, attributes: Record<string, string>, last: { X: number; Y: number }): Point[] {
switch (name) {
case 'line': {
- const x1 = parseInt(attributes.x1);
- const x2 = parseInt(attributes.x2);
- const y1 = parseInt(attributes.y1);
- const y2 = parseInt(attributes.y2);
+ const x1 = +attributes.x1;
+ const x2 = +attributes.x2;
+ const y1 = +attributes.y1;
+ const y2 = +attributes.y2;
return [
{ X: x1, Y: y1 },
{ X: x1, Y: y1 },
@@ -642,10 +760,10 @@ export function SVGToBezier(name: SVGType, attributes: any): Point[] {
case 'circle':
case 'ellipse': {
const c = 0.551915024494;
- const centerX = parseInt(attributes.cx);
- const centerY = parseInt(attributes.cy);
- const radiusX = parseInt(attributes.rx) || parseInt(attributes.r);
- const radiusY = parseInt(attributes.ry) || parseInt(attributes.r);
+ const centerX = +attributes.cx;
+ const centerY = +attributes.cy;
+ const radiusX = +attributes.rx || +attributes.r;
+ const radiusY = +attributes.ry || +attributes.r;
return [
{ X: centerX, Y: centerY + radiusY },
{ X: centerX + c * radiusX, Y: centerY + radiusY },
@@ -666,10 +784,10 @@ export function SVGToBezier(name: SVGType, attributes: any): Point[] {
];
}
case 'rect': {
- const x = parseInt(attributes.x);
- const y = parseInt(attributes.y);
- const width = parseInt(attributes.width);
- const height = parseInt(attributes.height);
+ const x = +attributes.x;
+ const y = +attributes.y;
+ const width = +attributes.width;
+ const height = +attributes.height;
return [
{ X: x, Y: y },
{ X: x, Y: y },
@@ -690,56 +808,73 @@ export function SVGToBezier(name: SVGType, attributes: any): Point[] {
];
}
case 'path': {
- const coordList: Point[] = [];
- const startPt = attributes.d.match(/M(-?\d+\.?\d*),(-?\d+\.?\d*)/);
- coordList.push({ X: parseInt(startPt[1]), Y: parseInt(startPt[2]) });
- const matches: RegExpMatchArray[] = Array.from(
- attributes.d.matchAll(/Q(-?\d+\.?\d*),(-?\d+\.?\d*) (-?\d+\.?\d*),(-?\d+\.?\d*)|C(-?\d+\.?\d*),(-?\d+\.?\d*) (-?\d+\.?\d*),(-?\d+\.?\d*) (-?\d+\.?\d*),(-?\d+\.?\d*)|L(-?\d+\.?\d*),(-?\d+\.?\d*)/g)
+ const cmds = new Map<string, number>([
+ ['A', 7],
+ ['C', 6],
+ ['Q', 4],
+ ['L', 2],
+ ['V', 1],
+ ['H', 1],
+ ['Z', 0],
+ ['M', 2],
+ ]);
+ const cmdReg = (letter: string) => `${letter}?${numberRange(cmds.get(letter)??0).map(() => '[, ]?(-?\\d*\\.?\\d*)').join('')}`; // prettier-ignore
+ const pathdata = convertRelativePathCmdsToAbsolute(
+ attributes.d
+ .replace(/([0-9])-/g, '$1,-') // numbers are smooshed together - put a ',' between number-number => number,-number
+ .replace(/([.][0-9]+)(?=\.)/g, '$1,') // numbers are smooshed together - put a ',' between .number.number => .number,.number
+ .trim()
);
- let lastPt: Point = startPt;
- matches.forEach(match => {
- if (match[0].startsWith('Q')) {
- coordList.push({ X: parseInt(match[1]), Y: parseInt(match[2]) });
- coordList.push({ X: parseInt(match[1]), Y: parseInt(match[2]) });
- coordList.push({ X: parseInt(match[3]), Y: parseInt(match[4]) });
- coordList.push({ X: parseInt(match[3]), Y: parseInt(match[4]) });
- lastPt = { X: parseInt(match[3]), Y: parseInt(match[4]) };
- } else if (match[0].startsWith('C')) {
- coordList.push({ X: parseInt(match[5]), Y: parseInt(match[6]) });
- coordList.push({ X: parseInt(match[7]), Y: parseInt(match[8]) });
- coordList.push({ X: parseInt(match[9]), Y: parseInt(match[10]) });
- coordList.push({ X: parseInt(match[9]), Y: parseInt(match[10]) });
- lastPt = { X: parseInt(match[9]), Y: parseInt(match[10]) };
- } else {
- coordList.push(lastPt);
- coordList.push({ X: parseInt(match[11]), Y: parseInt(match[12]) });
- coordList.push({ X: parseInt(match[11]), Y: parseInt(match[12]) });
- coordList.push({ X: parseInt(match[11]), Y: parseInt(match[12]) });
- lastPt = { X: parseInt(match[11]), Y: parseInt(match[12]) };
- }
- });
- const hasZ = attributes.d.match(/Z/);
- if (hasZ) {
- coordList.push(lastPt);
- coordList.push({ X: parseInt(startPt[1]), Y: parseInt(startPt[2]) });
- coordList.push({ X: parseInt(startPt[1]), Y: parseInt(startPt[2]) });
- } else {
- coordList.pop();
- }
+ const move = pathdata.match(cmdReg('M'));
+ const start = move?.slice(1).map(v => +v) ?? [last.X, last.Y];
+ const coordList: Point[] = [];
+ for (let prev = coordList.lastElement() ?? { X: start[0], Y: start[1] },
+ pathcmd = pathdata.slice(move?.[0].length ?? 0).trim(),
+ m = move,
+ lastCmd = '';
+ pathcmd;
+ pathcmd = pathcmd.slice(m?.[0].length ?? 1).trim(),
+ prev = coordList.lastElement()
+ ) {
+ lastCmd = Array.from(cmds.keys()).includes(pathcmd[0]) ? pathcmd[0] : lastCmd; // command character is first, otherwise we're continuing coordinates for the last command
+ m = pathcmd.match(new RegExp(cmdReg(lastCmd)))!; // matches command + number parameters specific to command
+ switch (m ? lastCmd : 'error') {
+ case 'Q': // convert quadratic to Bezier
+ ((Q) => coordList.push(
+ prev,
+ { X: prev.X + (2 / 3) * (Q[0] - prev.X), Y: prev.Y + (2 / 3) * (Q[1] - prev.Y) },
+ { X: Q[2] + (2 / 3) * (Q[0] - Q[2]), Y: Q[3] + (2 / 3) * (Q[1] - Q[3]) },
+ { X: Q[2], Y: Q[3] }
+ ))([+m[1], +m[2], +m[3], +m[4]]);
+ break; case 'C': // bezier curve
+ coordList.push(prev, { X: +m[1], Y: +m[2] }, { X: +m[3], Y: +m[4] }, { X: +m[5], Y: +m[6] });
+ break; case 'L': // convert line to bezier
+ coordList.push(prev, prev, { X: +m[1], Y: +m[2] }, { X: +m[1], Y: +m[2] });
+ break; case 'H': // convert horiz line to bezier
+ coordList.push(prev, prev, { X: +m[1], Y: prev.Y }, { X: +m[1], Y: prev.Y });
+ break; case 'V': // convert vert line to bezier
+ coordList.push(prev, prev, { X: prev.X, Y: +m[1] }, { X: prev.X, Y: +m[1] });
+ break; case 'A': // convert arc to bezier
+ console.log('SKIPPING arc - conversion to bezier not implemented');
+ break; case 'Z':
+ break;
+ default:
+ // eslint-disable-next-line no-debugger
+ debugger;
+ } // prettier-ignore
+ } // prettier-ignore
return coordList;
}
case 'polygon': {
- const coords: RegExpMatchArray[] = Array.from(attributes.points.matchAll(/(-?\d+\.?\d*),(-?\d+\.?\d*)/g));
- let list: Point[] = [];
+ const coords = Array.from(attributes.points.matchAll(/(-?\d+\.?\d*),(-?\d+\.?\d*)/g));
+ const list: Point[] = [];
coords.forEach(coord => {
- list.push({ X: parseInt(coord[1]), Y: parseInt(coord[2]) });
- list.push({ X: parseInt(coord[1]), Y: parseInt(coord[2]) });
- list.push({ X: parseInt(coord[1]), Y: parseInt(coord[2]) });
- list.push({ X: parseInt(coord[1]), Y: parseInt(coord[2]) });
+ list.push({ X: +coord[1], Y: +coord[2] });
+ list.push({ X: +coord[1], Y: +coord[2] });
+ list.push({ X: +coord[1], Y: +coord[2] });
+ list.push({ X: +coord[1], Y: +coord[2] });
});
- const firstPts = list.splice(0, 2);
- list = list.concat(firstPts);
- return list;
+ return list.concat(list.splice(0, 2)); // repeat start point to close
}
default:
return [];