1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
|
import { Bezier } from "bezier-js";
import { action, computed, observable, reaction } from "mobx";
import { Doc } from "../../fields/Doc";
import { Document } from "../../fields/documentSchemas";
import { InkData, InkField, InkTool, PointData } from "../../fields/InkField";
import { List } from "../../fields/List";
import { listSpec } from "../../fields/Schema";
import { Cast, NumCast } from "../../fields/Types";
import { DocumentType } from "../documents/DocumentTypes";
import { CurrentUserUtils } from "../util/CurrentUserUtils";
import { SelectionManager } from "../util/SelectionManager";
import { undoBatch } from "../util/UndoManager";
import { InkingStroke } from "./InkingStroke";
export class InkStrokeProperties {
static Instance: InkStrokeProperties | undefined;
@observable _lock = false;
@observable _controlButton = false;
@observable _currentPoint = -1;
constructor() {
InkStrokeProperties.Instance = this;
reaction(() => this._controlButton, button => button && (CurrentUserUtils.SelectedTool = InkTool.None));
reaction(() => CurrentUserUtils.SelectedTool, tool => (tool !== InkTool.None) && (this._controlButton = false));
}
@computed get selectedInk() {
const inks = SelectionManager.Views().filter(i => Document(i.rootDoc).type === DocumentType.INK);
return inks.length ? inks : undefined;
}
/**
* Helper function that enables other functions to be applied to a particular ink instance.
* @param func The inputted function.
* @param requireCurrPoint Indicates whether the current selected point is needed.
*/
applyFunction = (func: (doc: Doc, ink: InkData, ptsXscale: number, ptsYscale: number) => { X: number, Y: number }[] | undefined, requireCurrPoint: boolean = false) => {
var appliedFunc = false;
this.selectedInk?.forEach(action(inkView => {
if (this.selectedInk?.length === 1 && (!requireCurrPoint || this._currentPoint !== -1)) {
const doc = Document(inkView.rootDoc);
if (doc.type === DocumentType.INK && doc.width && doc.height) {
const ink = Cast(doc.data, InkField)?.inkData;
if (ink) {
const oldXrange = (xs => ({ coord: NumCast(doc.x), min: Math.min(...xs), max: Math.max(...xs) }))(ink.map(p => p.X));
const oldYrange = (ys => ({ coord: NumCast(doc.y), min: Math.min(...ys), max: Math.max(...ys) }))(ink.map(p => p.Y));
const ptsXscale = ((NumCast(doc._width) - NumCast(doc.strokeWidth)) / ((oldXrange.max - oldXrange.min) || 1)) || 1;
const ptsYscale = ((NumCast(doc._height) - NumCast(doc.strokeWidth)) / ((oldYrange.max - oldYrange.min) || 1)) || 1;
const newPoints = func(doc, ink, ptsXscale, ptsYscale);
if (newPoints) {
const newXrange = (xs => ({ min: Math.min(...xs), max: Math.max(...xs) }))(newPoints.map(p => p.X));
const newYrange = (ys => ({ min: Math.min(...ys), max: Math.max(...ys) }))(newPoints.map(p => p.Y));
doc._width = (newXrange.max - newXrange.min) * ptsXscale + NumCast(doc.strokeWidth);
doc._height = (newYrange.max - newYrange.min) * ptsYscale + NumCast(doc.strokeWidth);
doc.x = (oldXrange.coord + (newXrange.min - oldXrange.min) * ptsXscale);
doc.y = (oldYrange.coord + (newYrange.min - oldYrange.min) * ptsYscale);
Doc.GetProto(doc).data = new InkField(newPoints);
appliedFunc = true;
}
}
}
}
}));
return appliedFunc;
}
/**
* Adds a new control point to the ink instance when editing its format.
* @param t T-Value of new control point
* @param i index of first control point of segment being split
* @param control The list of all control points of the ink.
*/
@undoBatch
@action
addPoints = (t: number, i: number, controls: { X: number, Y: number }[]) => {
this.applyFunction((doc: Doc, ink: InkData) => {
const array = [controls[i], controls[i + 1], controls[i + 2], controls[i + 3]];
const newsegs = new Bezier(array.map(p => ({ x: p.X, y: p.Y }))).split(t);
const splicepts = [...newsegs.left.points, ...newsegs.right.points];
controls.splice(i, 4, ...splicepts.map(p => ({ X: p.x, Y: p.y })));
// Updating the indices of the control points whose handle tangency has been broken.
doc.brokenInkIndices = new List(Cast(doc.brokenInkIndices, listSpec("number"), []).map(control => control > i ? control + 4 : control));
this._currentPoint = -1;
return controls;
});
}
/**
* Scales a handle point of a control point that is adjacent to a newly added one.
* @param isLeft Determines if the current control point is on the left or right side of the newly added one.
* @param start Beginning index of curve from the left control point to the newly added one.
* @param end Final index of curve from the newly added control point to its right neighbor.
*/
getScaledHandlePoint(isLeft: boolean, start: number, end: number, index: number, control: PointData, handle: PointData) {
const prevSize = end - start;
const newSize = isLeft ? index - start : end - index;
const handleVector = { X: control.X - handle.X, Y: control.Y - handle.Y };
return { X: handleVector.X * (newSize / prevSize), Y: handleVector.Y * (newSize / prevSize) };
}
/**
* Determines the position of the handle points of a newly added control point by finding the
* tangent vectors to the split curve at the new control. Given the properties of Bézier curves,
* the tangent vector to a control point is equivalent to the first/last (depending on the direction
* of the curve) leg of the Bézier curve's derivative.
* (Source: https://pages.mtu.edu/~shene/COURSES/cs3621/NOTES/spline/Bezier/bezier-der.html)
*
* @param C The curve represented by all points from the previous control until the newly added point.
* @param D The curve represented by all points from the newly added point to the next control.
* @param newControl The newly added control point.
*/
getNewHandlePoints = (C: PointData[], D: PointData[], newControl: PointData) => {
const [m, n] = [C.length, D.length];
let handleSizeA = Math.sqrt((Math.pow(newControl.X - C[0].X, 2)) + (Math.pow(newControl.Y - C[0].Y, 2)));
let handleSizeB = Math.sqrt((Math.pow(D[n - 1].X - newControl.X, 2)) + (Math.pow(D[n - 1].Y - newControl.Y, 2)));
// Scaling adjustments to improve the ratio between the magnitudes of the two handle lines.
// (Ensures that the new point added doesn't augment the inital shape of the curve much).
if (handleSizeA < 75 && handleSizeB < 75) {
handleSizeA *= 3;
handleSizeB *= 3;
}
if (Math.abs(handleSizeA - handleSizeB) < 50) {
handleSizeA *= 5;
handleSizeB *= 5;
} else if (Math.abs(handleSizeA - handleSizeB) < 150) {
handleSizeA *= 2;
handleSizeB *= 2;
}
// Finding the last leg of the derivative curve of C.
const dC = { X: (handleSizeA / n) * (C[m - 1].X - C[m - 2].X), Y: (handleSizeA / n) * (C[m - 1].Y - C[m - 2].Y) };
// Finding the first leg of the derivative curve of D.
const dD = { X: (handleSizeB / m) * (D[1].X - D[0].X), Y: (handleSizeB / m) * (D[1].Y - D[0].Y) };
const handleA = { X: newControl.X - dC.X, Y: newControl.Y - dC.Y };
const handleB = { X: newControl.X + dD.X, Y: newControl.Y + dD.Y };
return [handleA, handleB];
}
/**
* Deletes the current control point of the selected ink instance.
*/
@undoBatch
@action
deletePoints = () => this.applyFunction((doc: Doc, ink: InkData) => {
const newPoints: { X: number, Y: number }[] = [];
const toRemove = Math.floor(((this._currentPoint + 2) / 4));
const last = this._currentPoint === ink.length - 1;
for (let i = 0; i < ink.length; i++) {
if (Math.floor((i + 2) / 4) !== toRemove && (toRemove !== 0 || i > 3)) {
newPoints.push({ X: ink[i].X, Y: ink[i].Y });
}
}
doc.brokenInkIndices = new List(Cast(doc.brokenInkIndices, listSpec("number"), []).map(control => control >= toRemove * 4 ? control - 4 : control));
if (last) newPoints.splice(newPoints.length - 3, 2);
this._currentPoint = -1;
return newPoints.length < 4 ? undefined : newPoints;
}, true)
/**
* Rotates the entire selected ink instance.
* @param angle The angle at which to rotate the ink in radians.
*/
@undoBatch
@action
rotateInk = (angle: number) => {
this.applyFunction((doc: Doc, ink: InkData, xScale: number, yScale: number) => {
const oldXrange = (xs => ({ coord: NumCast(doc.x), min: Math.min(...xs), max: Math.max(...xs) }))(ink.map(p => p.X));
const oldYrange = (ys => ({ coord: NumCast(doc.y), min: Math.min(...ys), max: Math.max(...ys) }))(ink.map(p => p.Y));
const centerPoint = { X: (oldXrange.min + oldXrange.max) / 2, Y: (oldYrange.min + oldYrange.max) / 2 };
const newPoints = ink.map(i => {
const pt = { X: i.X - centerPoint.X, Y: i.Y - centerPoint.Y };
const newX = Math.cos(angle) * pt.X - Math.sin(angle) * pt.Y * yScale / xScale;
const newY = Math.sin(angle) * pt.X * xScale / yScale + Math.cos(angle) * pt.Y;
return { X: newX + centerPoint.X, Y: newY + centerPoint.Y };
});
doc.rotation = NumCast(doc.rotation) + angle;
return newPoints;
});
}
/**
* Handles the movement/scaling of a control point.
*/
@undoBatch
@action
moveControlPtHandle = (deltaX: number, deltaY: number, controlIndex: number) =>
this.applyFunction((doc: Doc, ink: InkData, xScale: number, yScale: number) => {
const order = controlIndex % 4;
const closed = InkingStroke.IsClosed(ink);
const newpts = ink.map((pt, i) => {
const leftHandlePoint = order === 0 && i === controlIndex + 1;
const rightHandlePoint = order === 0 && controlIndex !== 0 && i === controlIndex - 2;
if (controlIndex === i ||
leftHandlePoint ||
rightHandlePoint ||
(order === 0 && controlIndex !== 0 && i === controlIndex - 1) ||
((order === 0 || order === 3) && (controlIndex === 0 || controlIndex === ink.length - 1) && (i === 1 || i === ink.length - 2) && closed) ||
(order === 3 && i === controlIndex - 1) ||
(order === 3 && controlIndex !== ink.length - 1 && i === controlIndex + 1) ||
(order === 3 && controlIndex !== ink.length - 1 && i === controlIndex + 2) ||
((ink[0].X === ink[ink.length - 1].X) && (ink[0].Y === ink[ink.length - 1].Y) && (i === 0 || i === ink.length - 1) && (controlIndex === 0 || controlIndex === ink.length - 1))) {
return ({ X: pt.X + deltaX / xScale, Y: pt.Y + deltaY / yScale });
}
return pt;
});
return newpts;
})
public static nearestPtToStroke(ctrlPoints: { X: number, Y: number }[], refPt: { X: number, Y: number }, excludeSegs?: number[]) {
var distance = Number.MAX_SAFE_INTEGER;
var nearestT = -1;
var nearestSeg = -1;
var nearestPt = { X: 0, Y: 0 };
for (var i = 0; i < ctrlPoints.length - 3; i += 4) {
if (excludeSegs?.includes(i)) continue;
const array = [ctrlPoints[i], ctrlPoints[i + 1], ctrlPoints[i + 2], ctrlPoints[i + 3]];
const point = new Bezier(array.map(p => ({ x: p.X, y: p.Y }))).project({ x: refPt.X, y: refPt.Y });
if (point.t !== undefined) {
const dist = Math.sqrt((point.x - refPt.X) * (point.x - refPt.X) + (point.y - refPt.Y) * (point.y - refPt.Y));
if (dist < distance) {
distance = dist;
nearestT = point.t;
nearestSeg = i;
nearestPt = { X: point.x, Y: point.y };
}
}
}
return { distance, nearestT, nearestSeg, nearestPt };
}
/**
* Handles the movement/scaling of a control point.
*/
snapControl = (inkDoc: Doc, controlIndex: number) => {
const ink = Cast(inkDoc.data, InkField)?.inkData;
if (ink) {
const closed = InkingStroke.IsClosed(ink);
// figure out which segments we don't want to snap to - avoid the dragged control point's segment and the next and prev segments (when they exist -- ie not for endpoints of unclosed curve)
const thisseg = Math.floor(controlIndex / 4) * 4;
const which = controlIndex % 4;
const nextseg = which > 1 && (closed || controlIndex < ink.length - 1) ? (thisseg + 4) % ink.length : -1;
const prevseg = which < 2 && (closed || controlIndex > 0) ? (thisseg - 4 + ink.length) % ink.length : -1;
const refPt = ink[controlIndex];
const { nearestPt } = InkStrokeProperties.nearestPtToStroke(ink, refPt, [thisseg, prevseg, nextseg]);
// nearestPt is in inkDoc coordinates -- we need to compute the distance in screen coordinates.
// so we scale the X & Y distances by the internal ink scale factor and then transform the final distance by the ScreenToLocal.Scale of the inkDoc itself.
const oldXrange = (xs => ({ coord: NumCast(inkDoc.x), min: Math.min(...xs), max: Math.max(...xs) }))(ink.map(p => p.X));
const oldYrange = (ys => ({ coord: NumCast(inkDoc.y), min: Math.min(...ys), max: Math.max(...ys) }))(ink.map(p => p.Y));
const ptsXscale = ((NumCast(inkDoc._width) - NumCast(inkDoc.strokeWidth)) / ((oldXrange.max - oldXrange.min) || 1)) || 1;
const ptsYscale = ((NumCast(inkDoc._height) - NumCast(inkDoc.strokeWidth)) / ((oldYrange.max - oldYrange.min) || 1)) || 1;
const near = Math.sqrt((nearestPt.X - refPt.X) * (nearestPt.X - refPt.X) * ptsXscale * ptsXscale +
(nearestPt.Y - refPt.Y) * (nearestPt.Y - refPt.Y) * ptsYscale * ptsYscale);
if (near / (this.selectedInk?.lastElement().props.ScreenToLocalTransform().Scale || 1) < 10) {
return this.moveControlPtHandle((nearestPt.X - ink[controlIndex].X) * ptsXscale, (nearestPt.Y - ink[controlIndex].Y) * ptsYscale, controlIndex);
}
}
return false;
}
/**
* Snaps a control point with broken tangency back to synced rotation.
* @param handleIndexA The handle point that retains its current position.
* @param handleIndexB The handle point that is rotated to be 180 degrees from its opposite.
*/
snapHandleTangent = (controlIndex: number, handleIndexA: number, handleIndexB: number) => {
this.applyFunction((doc: Doc, ink: InkData) => {
const brokenIndices = Cast(doc.brokenInkIndices, listSpec("number"), []);
const ind = brokenIndices.findIndex(value => value === controlIndex);
if (ind !== -1) {
brokenIndices.splice(ind, 1);
const [controlPoint, handleA, handleB] = [ink[controlIndex], ink[handleIndexA], ink[handleIndexB]];
const oppositeHandleA = this.rotatePoint(handleA, controlPoint, Math.PI);
const angleDifference = this.angleChange(handleB, oppositeHandleA, controlPoint);
const inkCopy = ink.slice(); // have to make a new copy of the array to keep from corrupting undo/redo. without slicing, the same array will be stored in each undo step meaning earlier undo steps will be inadvertently updated to store the latest value.
inkCopy[handleIndexB] = this.rotatePoint(handleB, controlPoint, angleDifference);
return inkCopy;
}
});
}
/**
* Rotates the target point about the origin point for a given angle (radians).
*/
@action
rotatePoint = (target: PointData, origin: PointData, angle: number) => {
const rotatedTarget = { X: target.X - origin.X, Y: target.Y - origin.Y };
const newX = Math.cos(angle) * rotatedTarget.X - Math.sin(angle) * rotatedTarget.Y;
const newY = Math.sin(angle) * rotatedTarget.X + Math.cos(angle) * rotatedTarget.Y;
return { X: newX + origin.X, Y: newY + origin.Y };
}
/**
* Finds the angle (in radians) between two inputted vectors.
*
* α = arccos(a·b / |a|·|b|), where a and b are both vectors.
*/
angleBetweenTwoVectors = (vectorA: PointData, vectorB: PointData) => {
const magnitudeA = Math.sqrt(vectorA.X * vectorA.X + vectorA.Y * vectorA.Y);
const magnitudeB = Math.sqrt(vectorB.X * vectorB.X + vectorB.Y * vectorB.Y);
if (magnitudeA === 0 || magnitudeB === 0) return 0;
// Normalizing the vectors.
vectorA = { X: vectorA.X / magnitudeA, Y: vectorA.Y / magnitudeA };
vectorB = { X: vectorB.X / magnitudeB, Y: vectorB.Y / magnitudeB };
return Math.acos(vectorB.X * vectorA.X + vectorB.Y * vectorA.Y);
}
/**
* Finds the angle difference (in radians) between two vectors relative to an arbitrary origin.
*/
angleChange = (a: PointData, b: PointData, origin: PointData) => {
// Finding vector representation of inputted points relative to new origin.
const vectorA = { X: a.X - origin.X, Y: a.Y - origin.Y };
const vectorB = { X: b.X - origin.X, Y: b.Y - origin.Y };
const crossProduct = vectorB.X * vectorA.Y - vectorB.Y * vectorA.X;
// Determining whether rotation is clockwise or counterclockwise.
const sign = crossProduct < 0 ? 1 : -1;
const theta = this.angleBetweenTwoVectors(vectorA, vectorB);
return sign * theta;
}
/**
* Handles the movement/scaling of a handle point.
*/
@undoBatch
@action
moveTangentHandle = (deltaX: number, deltaY: number, handleIndex: number, oppositeHandleIndex: number, controlIndex: number) =>
this.applyFunction((doc: Doc, ink: InkData, xScale: number, yScale: number) => {
const closed = InkingStroke.IsClosed(ink);
const oldHandlePoint = ink[handleIndex];
const oppositeHandlePoint = ink[oppositeHandleIndex];
const controlPoint = ink[controlIndex];
const newHandlePoint = { X: ink[handleIndex].X - deltaX / xScale, Y: ink[handleIndex].Y - deltaY / yScale };
const inkCopy = ink.slice();
inkCopy[handleIndex] = newHandlePoint;
const brokenIndices = Cast(doc.brokenInkIndices, listSpec("number"));
const equivIndex = closed ? (controlIndex === 0 ? ink.length - 1 : controlIndex === ink.length - 1 ? 0 : -1) : -1;
// Rotate opposite handle if user hasn't held 'Alt' key or not first/final control (which have only 1 handle).
if ((!brokenIndices || (!brokenIndices?.includes(controlIndex) && !brokenIndices?.includes(equivIndex))) &&
(closed || (handleIndex !== 1 && handleIndex !== ink.length - 2))) {
const angle = this.angleChange(oldHandlePoint, newHandlePoint, controlPoint);
inkCopy[oppositeHandleIndex] = this.rotatePoint(oppositeHandlePoint, controlPoint, angle);
}
return inkCopy;
})
}
|