-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgeometryutils.cpp
More file actions
335 lines (279 loc) · 11 KB
/
geometryutils.cpp
File metadata and controls
335 lines (279 loc) · 11 KB
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
#include "geometryutils.h"
#include <QStringBuilder>
#include <algorithm>
#include <optional>
#include <random>
using namespace Qt::StringLiterals;
GeometryUtils::GeometryUtils(QObject *parent)
: QObject{parent}
{
}
qreal GeometryUtils::lerp(qreal from, qreal to, qreal t)
{
return from + (to - from) * t;
}
static qreal dot(const QPointF a, const QPointF b)
{
return a.x() * b.x() + a.y() * b.y();
}
static qreal magnitude2(const QPointF point)
{
return point.x() * point.x() + point.y() * point.y();
}
// find a projection of `point` onto a line between points `a` and `b`.
static QPointF projection(QPointF a, QPointF b, QPointF point)
{
// step 1: translate into {0,0} origin
b -= a;
point -= a;
// step 2: find a projection (but don't multiply it by the `end` vector)
QPointF proj = dot(point, b) / magnitude2(b) * b;
// step 3: restore translation
return proj + a;
}
qreal GeometryUtils::linearPosition(QPointF start, QPointF end, QPointF position)
{
// step 1: translate into {0,0} origin
end -= start;
position -= start;
start = {0.0, 0.0};
// step 2: find a projection (but don't multiply it by the `end` vector)
return std::clamp(dot(position, end) / magnitude2(end), qreal(0.0), qreal(1.0));
}
QPointF GeometryUtils::planarPosition(QPointF start, QPointF end, QPointF zero, QPointF position)
{
const qreal directPosition = linearPosition(start, end, position);
const qreal directPositionClamped = std::clamp(directPosition, 0.0, 1.0);
const QPointF zeroProj = projection(start, end, zero);
const qreal perpendicularPosition = linearPosition(zero, zeroProj, position);
const qreal perpendicularPositionClamped = std::clamp(perpendicularPosition, 0.0, 1.0);
return QPointF(directPositionClamped, perpendicularPositionClamped);
}
namespace
{
struct SnapCandidate
{
QVector2D target;
float distance;
void min(const SnapCandidate newCandidate)
{
if (newCandidate.distance < distance) {
*this = newCandidate;
}
}
void min(const std::optional<SnapCandidate> maybeNewCandidate)
{
if (maybeNewCandidate.has_value() && maybeNewCandidate->distance < distance) {
*this = *maybeNewCandidate;
}
}
};
SnapCandidate makeVertexCandidate(const QVector2D vertex, const QVector2D position)
{
return SnapCandidate {
.target = vertex,
.distance = (vertex - position).length(),
};
}
std::optional<SnapCandidate> makeProjectionCandidate(const QVector2D base, const QVector2D position)
{
const QVector2D proj = QVector2D::dotProduct(position, base) / base.lengthSquared() * base;
const bool sameDirectionX = base.x() < 0.0 == proj.x() < 0.0;
const bool sameDirectionY = base.y() < 0.0 == proj.y() < 0.0;
if (sameDirectionX && sameDirectionY && proj.lengthSquared() <= base.lengthSquared()) {
return std::make_optional(SnapCandidate {
.target = proj,
.distance = (proj - position).length(),
});
}
return {};
}
std::optional<SnapCandidate> makeProjectionCandidate(const QVector2D lineA, const QVector2D lineB, const QVector2D position)
{
std::optional<SnapCandidate> maybeCandidate = makeProjectionCandidate(lineB - lineA, position - lineA);
if (maybeCandidate.has_value()) {
maybeCandidate->target += lineA;
}
return maybeCandidate;
}
float sign(QVector2D position, QVector2D lineA, QVector2D lineB)
{
return (position.x() - lineB.x()) * (lineA.y() - lineB.y()) - (lineA.x() - lineB.x()) * (position.y() - lineB.y());
}
bool isPositionInsideTriangle(QVector2D vertexA, QVector2D vertexB, QVector2D vertexC, QVector2D position)
{
const float sign1 = sign(position, vertexA, vertexB);
const float sign2 = sign(position, vertexB, vertexC);
const float sign3 = sign(position, vertexC, vertexA);
const bool allNeg = (sign1 < 0.0) || (sign2 < 0.0) || (sign3 < 0.0);
const bool allPos = (sign1 > 0.0) || (sign2 > 0.0) || (sign3 > 0.0);
return !(allNeg && allPos);
}
}
QPointF GeometryUtils::snapPointToTriangle(QPointF vertexA, QPointF vertexB, QPointF vertexC, QPointF position)
{
return snapVectorToTriangle(QVector2D(vertexA), QVector2D(vertexB), QVector2D(vertexC), QVector2D(position)).toPointF();
}
QVector2D GeometryUtils::snapVectorToTriangle(QVector2D vertexA, QVector2D vertexB, QVector2D vertexC, QVector2D position)
{
if (isPositionInsideTriangle(vertexA, vertexB, vertexC, position)) {
// the point is inside, no further actions needed
return position;
}
SnapCandidate bestSnapCandidate = makeVertexCandidate(vertexA, position);
bestSnapCandidate.min(makeVertexCandidate(vertexB, position));
bestSnapCandidate.min(makeVertexCandidate(vertexC, position));
bestSnapCandidate.min(makeProjectionCandidate(vertexA, vertexB, position));
bestSnapCandidate.min(makeProjectionCandidate(vertexB, vertexC, position));
bestSnapCandidate.min(makeProjectionCandidate(vertexC, vertexA, position));
return bestSnapCandidate.target;
}
QList<QPointF> GeometryUtils::randomUnitTriangle()
{
constexpr const unsigned int NUM_VERTICES = 3;
std::uniform_real_distribution<qreal> unitDist(0.0, 1.0);
std::uniform_int_distribution boolDist{0, 1};
std::uniform_int_distribution<unsigned int> edgeDist{0, NUM_VERTICES - 1};
std::uniform_int_distribution<unsigned int> rotationDist{0, 3};
std::random_device rd;
std::default_random_engine rng(rd());
auto getUnit = [&]() -> qreal { return unitDist(rng); };
auto getBool = [&]() -> bool { return boolDist(rng) != 0; };
auto getEdge = [&]() -> unsigned int { return edgeDist(rng); };
auto get2Edges = [&]() -> std::array<unsigned int, 2> {
// pick any two out of three == pick one to discard
std::array<unsigned int, 2> edges;
const auto ignore = getEdge();
for (int e = 0, v = 0; e < 2 && v < NUM_VERTICES; v += 1) {
if (v != ignore) {
edges[e] = v;
e += 1;
}
}
if (getBool()) {
std::swap(edges[0], edges[1]);
}
return edges;
};
auto getRotations = [&]() -> unsigned int { return rotationDist(rng); };
auto rotate90 = [](QPointF point) -> QPointF {
// step 1: translate unit point to origin 0.0 (with extents -0.5..0.5)
point -= QPointF(0.5, 0.5);
// step 2: rotate 90deg CV
point = {-point.y(), point.x()};
// step 3: translate back to unit square
point += QPointF(0.5, 0.5);
return point;
};
QList<QPointF> vertices{NUM_VERTICES};
// Random shape:
// 0. Two on the same edge, third needs to be on the opposite edge.
// Then pick any two, and make sure they are on the opposite perpendicular edges too.
// 1. All vertices are on three random but different edges.
// Then pick one of the edges perpendicular to the empty one, and move its point toward the empty edge.
const auto shapeStrategy = getBool();
if (shapeStrategy) {
// two on the same (left) edge, i.e. x=0, y=rand
vertices[0] = {0.0, getUnit()};
vertices[1] = {0.0, getUnit()};
// third is on the right edge
vertices[2] = {1.0, getUnit()};
// split vertically
const auto [edgeTop, edgeBottom] = get2Edges();
vertices[edgeTop].setY(0.0);
vertices[edgeBottom].setY(1.0);
} else {
// three different edges
vertices[0] = {0.0, getUnit()}; // left
vertices[1] = {getUnit(), 0.0}; // top
vertices[2] = {1.0, getUnit()}; // right
// pick either left or right
const auto vertex = getBool() ? 0 : 2;
// move it toward bottom edge
vertices[vertex].setY(1.0);
}
// random rotation: number of times vertices need to be rotates 90 degrees
const auto rotations = getRotations();
for (int r = 0; r < rotations; r++) {
for (QPointF &point : vertices) {
point = rotate90(point);
}
}
// random swap vertices
std::shuffle(vertices.begin(), vertices.end(), rng);
return vertices;
}
namespace
{
float crossProduct(QVector2D a, QVector2D b)
{
return a[0] * b[1] - a[1] * b[0];
}
// Returns:
// > 0: The triangle has a CCW winding (front-facing).
// < 0: The triangle has a CW winding (back-facing).
// = 0: The points are collinear, or the triangle has zero area.
float triangleWinding(QPointF vertexA, QPointF vertexB, QPointF vertexC)
{
const QVector2D a = QVector2D(vertexA - vertexC);
const QVector2D b = QVector2D(vertexB - vertexC);
return crossProduct(a, b);
}
// Translate line defined as two end points A and B by a given vector
std::pair<QPointF, QPointF> translateLine(const QPointF lineA, const QPointF lineB, const QVector2D vector)
{
const auto lineAEx = (QVector2D(lineA) + vector).toPointF();
const auto lineBEx = (QVector2D(lineB) + vector).toPointF();
return {lineAEx, lineBEx};
}
std::pair<QPointF, QPointF> translateLine(const QPointF lineA, const QPointF lineB, const QPointF origin, qreal distance)
{
// step 1: find a perpendicular vector that points away from the `origin` point
const QPointF proj = projection(lineA, lineB, origin);
const QVector2D perpendicular = QVector2D(proj - origin);
// step 2: scale it down to the required distance
const QVector2D extrusion = perpendicular.normalized() * distance;
// step 3: translate the line
return translateLine(lineA, lineB, extrusion);
}
inline QString svgNumber(qreal number)
{
return u' ' % QString::number(number, 'f') % u' ';
}
inline QString svgPoint(QPointF point)
{
return svgNumber(point.x()) % svgNumber(point.y());
}
inline QString svgArc(QPointF point, qreal radius)
{
const QString r = svgNumber(radius);
// A rx ry x-axis-rotation large-arc-flag sweep-flag x y
return u" A"_s % r % r % u"0 0 1" % svgPoint(point);
}
}
QString GeometryUtils::roundedTriangleOutlineSvgPath(QPointF vertexA, QPointF vertexB, QPointF vertexC, qreal cornerRadius)
{
// step 1: ensure consistent winding order
if (triangleWinding(vertexA, vertexB, vertexC) < 0.0) {
std::swap(vertexB, vertexC);
}
// step 2: extrude lines outwards
const auto lineAB = translateLine(vertexA, vertexB, vertexC, cornerRadius);
const auto lineBC = translateLine(vertexB, vertexC, vertexA, cornerRadius);
const auto lineCA = translateLine(vertexC, vertexA, vertexB, cornerRadius);
const QString svg = u"M"_s % svgPoint(lineAB.first)
% u'L' % svgPoint(lineAB.second) % svgArc(lineBC.first, cornerRadius)
% u'L' % svgPoint(lineBC.second) % svgArc(lineCA.first, cornerRadius)
% u'L' % svgPoint(lineCA.second) % svgArc(lineAB.first, cornerRadius)
% u'z';
return svg;
}
QList<QPointF> GeometryUtils::scaledPoints(const QList<QPointF> &points, QSizeF scale)
{
QList<QPointF> scaled = points;
for (QPointF &point : scaled) {
point = QPointF(point.x() * scale.width(), point.y() * scale.height());
}
return scaled;
}
#include "moc_geometryutils.cpp"