-
-
Notifications
You must be signed in to change notification settings - Fork 102
/
PathMutations.swift
362 lines (311 loc) · 10.9 KB
/
PathMutations.swift
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
353
354
355
356
357
358
359
360
361
362
// Copyright 2021 Tokamak contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Created by Max Desiatov on 20/06/2021.
//
import Foundation
public extension Path {
private mutating func append(_ other: Storage, transform: CGAffineTransform = .identity) {
guard other != .empty else { return }
// If self.storage is empty, replace with other storage.
// Otherwise append elements to current storage.
switch (storage, transform.isIdentity) {
case (.empty, true):
storage = other
default:
append(other.elements, transform: transform)
}
}
private mutating func append(_ elements: [Element], transform: CGAffineTransform = .identity) {
guard !elements.isEmpty else { return }
let elements_: [Element]
if transform.isIdentity {
elements_ = elements
} else {
elements_ = elements.map { transform.transform(element: $0) }
}
switch storage {
case let .path(pathBox):
pathBox.elements.append(contentsOf: elements_)
default:
storage = .path(_PathBox(elements: storage.elements + elements_))
}
}
mutating func move(to p: CGPoint) {
append([.move(to: p)])
}
mutating func addLine(to p: CGPoint) {
append([.line(to: p)])
}
mutating func addQuadCurve(to p: CGPoint, control cp: CGPoint) {
append([.quadCurve(to: p, control: cp)])
}
mutating func addCurve(to p: CGPoint, control1 cp1: CGPoint, control2 cp2: CGPoint) {
append([.curve(to: p, control1: cp1, control2: cp2)])
}
mutating func closeSubpath() {
append([.closeSubpath])
}
mutating func addRect(_ rect: CGRect, transform: CGAffineTransform = .identity) {
append(.rect(rect), transform: transform)
}
mutating func addRoundedRect(
in rect: CGRect,
cornerSize: CGSize,
style: RoundedCornerStyle = .circular,
transform: CGAffineTransform = .identity
) {
append(
.roundedRect(FixedRoundedRect(rect: rect, cornerSize: cornerSize, style: style)),
transform: transform
)
}
mutating func addEllipse(in rect: CGRect, transform: CGAffineTransform = .identity) {
append(.ellipse(rect), transform: transform)
}
mutating func addRects(_ rects: [CGRect], transform: CGAffineTransform = .identity) {
rects.forEach { addRect($0, transform: transform) }
}
mutating func addLines(_ lines: [CGPoint]) {
lines.forEach { addLine(to: $0) }
}
mutating func addRelativeArc(
center: CGPoint,
radius: CGFloat,
startAngle: Angle,
delta: Angle,
transform: CGAffineTransform = .identity
) {
addArc(
center: center,
radius: radius,
startAngle: startAngle,
endAngle: startAngle + delta,
clockwise: false,
transform: transform
)
}
// There's a great article on bezier curves here:
// https://pomax.github.io/bezierinfo
// FIXME: Handle negative delta
mutating func addArc(
center: CGPoint,
radius: CGFloat,
startAngle: Angle,
endAngle: Angle,
clockwise: Bool,
transform: CGAffineTransform = .identity
) {
let arc = getArc(
center: center,
radius: radius,
startAngle: endAngle,
endAngle: endAngle + (.radians(.pi * 2) - endAngle) + startAngle,
clockwise: false
)
append(arc, transform: transform)
}
// FIXME: How does this arc method work?
mutating func addArc(
tangent1End p1: CGPoint,
tangent2End p2: CGPoint,
radius: CGFloat,
transform: CGAffineTransform = .identity
) {
let arc = getArcFromTangents(
tangent1Start: currentPoint ?? .zero,
tangentIntersect: p1,
tangent2End: p2,
radius: radius
)
append(arc, transform: transform)
}
mutating func addPath(_ path: Path, transform: CGAffineTransform = .identity) {
append(path.storage, transform: transform)
}
}
func getArc(
center: CGPoint,
radius: CGFloat,
startAngle: Angle,
endAngle: Angle,
clockwise: Bool
) -> [Path.Element] {
if clockwise {
return getArc(
center: center,
radius: radius,
startAngle: endAngle,
endAngle: endAngle + (.radians(.pi * 2) - endAngle) + startAngle,
clockwise: false
)
} else {
let angle = abs(startAngle.radians - endAngle.radians)
if angle > .pi / 2 {
// Split the angle into 90º chunks
let chunk1 = Angle.radians(startAngle.radians + (.pi / 2))
return getArc(
center: center,
radius: radius,
startAngle: startAngle,
endAngle: chunk1,
clockwise: clockwise
) +
getArc(
center: center,
radius: radius,
startAngle: chunk1,
endAngle: endAngle,
clockwise: clockwise
)
} else {
let angle = CGFloat(angle)
let endPoint = CGPoint(
x: (radius * cos(angle)) + center.x,
y: (radius * sin(angle)) + center.y
)
let l = (4 / 3) * tan(angle / 4)
let c1 = CGPoint(x: radius + center.x, y: (l * radius) + center.y)
let c2 = CGPoint(
x: ((cos(angle) + l * sin(angle)) * radius) + center.x,
y: ((sin(angle) - l * cos(angle)) * radius) + center.y
)
return [
.curve(
to: endPoint.rotate(startAngle, around: center),
control1: c1.rotate(startAngle, around: center),
control2: c2.rotate(startAngle, around: center)
),
]
}
}
}
private extension CGPoint {
static func + (a: CGPoint, b: CGPoint) -> CGPoint {
CGPoint(x: a.x + b.x, y: a.y + b.y)
}
static func - (a: CGPoint, b: CGPoint) -> CGPoint {
CGPoint(x: a.x - b.x, y: a.y - b.y)
}
static func * (a: CGPoint, b: CGPoint) -> CGPoint {
CGPoint(x: a.x * b.x, y: a.y * b.y)
}
static func * (a: CGPoint, b: Double) -> CGPoint {
a * CGPoint(x: b, y: b)
}
var magnitude: Double {
sqrt(x * x + y * y)
}
/// Changes the magnitude of the vector on the origin's
/// coordinate system.
func withMagnitude(_ newValue: Double, origin: CGPoint = .zero) -> CGPoint {
var copy = self - origin
let scale = newValue / copy.magnitude
// swiftlint:disable:next shorthand_operator
copy = copy * scale
return copy + origin
}
/// The angle on the origin's coordinate system from this to the
/// given vector either clockwise or counterclockwise. The return
/// value is in the closed range [0º, 360º].
func angle(
to other: CGPoint,
clockwise: Bool,
origin: CGPoint = .zero
) -> (this: Angle, other: Angle, between: Angle) {
let a = self - origin, b = other - origin
let this = atan2(a.y, a.x), other = atan2(b.y, b.x)
let radians = this - other
let normalized = radians > 0 ? radians : radians + (2 * .pi)
// Convert to clockwise if requested
let adjusted = clockwise ? normalized : (2 * .pi) - normalized
return (.radians(this), .radians(other), .radians(adjusted))
}
static func bisector(a: CGPoint, b: CGPoint, origin: CGPoint = .zero) -> CGPoint {
let a = a - origin, b = b - origin
return ((a * b.magnitude) + (b * a.magnitude)) + origin
}
}
private extension Angle {
/// Returns an angle between 0 and 2π.
var normalized: Angle {
let remainder = radians.truncatingRemainder(dividingBy: 2 * .pi)
return .radians(remainder > 0 ? remainder : (2 * .pi) + remainder)
}
/// Takes a normalized angle and returns an angle in the closed range [0, 180º].
var smallest: Angle {
assert(radians >= 0 && radians <= 2 * .pi, "Angle not normalized")
return .radians(radians <= .pi ? radians : (2 * .pi) - radians)
}
}
func getArcFromTangents(
tangent1Start p1: CGPoint,
tangentIntersect intersect: CGPoint,
tangent2End p2: CGPoint,
radius: Double
) -> [Path.Element] {
let (p1RawAngle, p2RawAngle, rawDelta) = p1.angle(
to: p2,
clockwise: true, origin: intersect
)
// delta is the angle between the two tangents that is in the closed range [0º, 180º].
let delta = rawDelta.smallest
// The tangency points of the arc and the tangents form a triangle along with the
// tangent intersects and center. The angle of both triangles in the vertex of
// the tangent intersects is known to be theta. That is because the triangles are
// equal and the combined angle (the angle between the tangents) has been found to
// be delta. Additionally, the line segment consiting from the center to either tangency
// point is known to be the radius. Thus, we can use the sin function to find the length
// of the segment connecting the center to the tangent intersects.
let theta = delta * 0.5
let centerToIntersectLength = radius / abs(sin(theta.radians))
// Create a bisector between the tangents to get a vector pointing
// to the direction of the center point. Then, using the previously
// found length, adjust the vector's magnitude to actually point to the
// center point.
let centerDirection = CGPoint.bisector(a: p1, b: p2, origin: intersect)
let center = centerDirection.withMagnitude(centerToIntersectLength, origin: intersect)
// We've got the clockwise angles of both tangents from calculating
// the angle between them. After normalizing them, knowing that the
// start and end rays are orthogonal, we can add a right angle to
// p1Angle and subtract it from p2Angle or vice versa. Delta is known
// to be less than 180º, so this is the reason must always be rotated
// in opposite ways to "turn" towards each other.
let (p1Angle, p2Angle) = (p1RawAngle.normalized, p2RawAngle.normalized)
let right = Angle.radians(.pi / 2)
// The end angle has a greater (normalized clockwise) angle than
// the start angle. Thus, if the normalized difference of the p1
// and p2 angles is greater than what it's supposed to be (delta,
// the angle between the tangents), then their order is reversed.
// So the angle of the end ray is tangent to the segment containing
// p1.
//
// The angle difference is normalized (instead of taking
// the magnitude) because the order of subtraction matters.
let p1IsEnd = (p2Angle - p1Angle).normalized.radians - 0.0001 >= delta.radians.magnitude
let (angle1, angle2) = !p1IsEnd ?
((p1Angle - right).normalized, (p2Angle + right).normalized) :
((p1Angle + right).normalized, (p2Angle - right).normalized)
// angle1, which is associated with p1, will always be used as the
// startAngle. But if this angle is actually the end angle, we
// want clockwise to become false.
let clockwise = !p1IsEnd
return getArc(
center: center,
radius: radius,
startAngle: angle1,
endAngle: angle2,
clockwise: clockwise
)
}