This repository has been archived by the owner on Aug 8, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
collision_index.cpp
375 lines (316 loc) · 17.3 KB
/
collision_index.cpp
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
363
364
365
366
367
368
369
370
371
372
373
374
375
#include <mbgl/text/collision_index.hpp>
#include <mbgl/layout/symbol_instance.hpp>
#include <mbgl/geometry/feature_index.hpp>
#include <mbgl/math/log2.hpp>
#include <mbgl/util/constants.hpp>
#include <mbgl/util/math.hpp>
#include <mbgl/math/minmax.hpp>
#include <mbgl/util/intersection_tests.hpp>
#include <mbgl/layout/symbol_projection.hpp>
#include <mapbox/geometry/envelope.hpp>
#include <mbgl/renderer/buckets/symbol_bucket.hpp> // For PlacedSymbol: pull out to another location
#include <cmath>
namespace mbgl {
// When a symbol crosses the edge that causes it to be included in
// collision detection, it will cause changes in the symbols around
// it. This constant specifies how many pixels to pad the edge of
// the viewport for collision detection so that the bulk of the changes
// occur offscreen. Making this constant greater increases label
// stability, but it's expensive.
static const float viewportPadding = 100;
CollisionIndex::CollisionIndex(const TransformState& transformState_)
: transformState(transformState_)
, collisionGrid(transformState.getSize().width + 2 * viewportPadding, transformState.getSize().height + 2 * viewportPadding, 25)
, ignoredGrid(transformState.getSize().width + 2 * viewportPadding, transformState.getSize().height + 2 * viewportPadding, 25)
, screenRightBoundary(transformState.getSize().width + viewportPadding)
, screenBottomBoundary(transformState.getSize().height + viewportPadding)
, gridRightBoundary(transformState.getSize().width + 2 * viewportPadding)
, gridBottomBoundary(transformState.getSize().height + 2 * viewportPadding)
, pitchFactor(std::cos(transformState.getPitch()) * transformState.getCameraToCenterDistance())
{}
float CollisionIndex::approximateTileDistance(const TileDistance& tileDistance, const float lastSegmentAngle, const float pixelsToTileUnits, const float cameraToAnchorDistance, const bool pitchWithMap) {
// This is a quick and dirty solution for chosing which collision circles to use (since collision circles are
// laid out in tile units). Ideally, I think we should generate collision circles on the fly in viewport coordinates
// at the time we do collision detection.
// incidenceStretch is the ratio of how much y space a label takes up on a tile while drawn perpendicular to the viewport vs
// how much space it would take up if it were drawn flat on the tile
// Using law of sines, camera_to_anchor/sin(ground_angle) = camera_to_center/sin(incidence_angle)
// Incidence angle 90 -> head on, sin(incidence_angle) = 1, no stretch
// Incidence angle 1 -> very oblique, sin(incidence_angle) =~ 0, lots of stretch
// ground_angle = u_pitch + PI/2 -> sin(ground_angle) = cos(u_pitch)
// incidenceStretch = 1 / sin(incidenceAngle)
const float incidenceStretch = pitchWithMap ? 1 : cameraToAnchorDistance / pitchFactor;
const float lastSegmentTile = tileDistance.lastSegmentViewportDistance * pixelsToTileUnits;
return tileDistance.prevTileDistance +
lastSegmentTile +
(incidenceStretch - 1) * lastSegmentTile * std::abs(std::sin(lastSegmentAngle));
}
bool CollisionIndex::isOffscreen(const CollisionBox& box) const {
return box.px2 < viewportPadding || box.px1 >= screenRightBoundary || box.py2 < viewportPadding || box.py1 >= screenBottomBoundary;
}
bool CollisionIndex::isInsideGrid(const CollisionBox& box) const {
return box.px2 >= 0 && box.px1 < gridRightBoundary && box.py2 >= 0 && box.py1 < gridBottomBoundary;
}
CollisionTileBoundaries CollisionIndex::projectTileBoundaries(const mat4& posMatrix) const {
Point<float> topLeft = projectPoint(posMatrix, { 0, 0 });
Point<float> bottomRight = projectPoint(posMatrix, { util::EXTENT, util::EXTENT });
return {{ topLeft.x, topLeft.y, bottomRight.x, bottomRight.y }};
}
bool CollisionIndex::isInsideTile(const CollisionBox& box, const CollisionTileBoundaries& tileBoundaries) const {
// This check is only well defined when the tile boundaries are axis-aligned
// We are relying on it only being used in MapMode::Tile, where that is always the case
return box.px1 >= tileBoundaries[0] && box.py1 >= tileBoundaries[1] && box.px2 < tileBoundaries[2] && box.py2 < tileBoundaries[3];
}
std::pair<bool,bool> CollisionIndex::placeFeature(CollisionFeature& feature,
Point<float> shift,
const mat4& posMatrix,
const mat4& labelPlaneMatrix,
const float textPixelRatio,
PlacedSymbol& symbol,
const float scale,
const float fontSize,
const bool allowOverlap,
const bool pitchWithMap,
const bool collisionDebug,
const optional<CollisionTileBoundaries>& avoidEdges,
const optional<std::function<bool(const IndexedSubfeature&)>> collisionGroupPredicate) {
if (!feature.alongLine) {
CollisionBox& box = feature.boxes.front();
const auto projectedPoint = projectAndGetPerspectiveRatio(posMatrix, box.anchor);
const float tileToViewport = textPixelRatio * projectedPoint.second;
box.px1 = (box.x1 + shift.x) * tileToViewport + projectedPoint.first.x;
box.py1 = (box.y1 + shift.y) * tileToViewport + projectedPoint.first.y;
box.px2 = (box.x2 + shift.x) * tileToViewport + projectedPoint.first.x;
box.py2 = (box.y2 + shift.y) * tileToViewport + projectedPoint.first.y;
if ((avoidEdges && !isInsideTile(box, *avoidEdges)) ||
!isInsideGrid(box) ||
(!allowOverlap && collisionGrid.hitTest({{ box.px1, box.py1 }, { box.px2, box.py2 }}, collisionGroupPredicate))) {
return { false, false };
}
return {true, isOffscreen(box)};
} else {
return placeLineFeature(feature, posMatrix, labelPlaneMatrix, textPixelRatio, symbol, scale, fontSize, allowOverlap, pitchWithMap, collisionDebug, avoidEdges, collisionGroupPredicate);
}
}
std::pair<bool,bool> CollisionIndex::placeLineFeature(CollisionFeature& feature,
const mat4& posMatrix,
const mat4& labelPlaneMatrix,
const float textPixelRatio,
PlacedSymbol& symbol,
const float scale,
const float fontSize,
const bool allowOverlap,
const bool pitchWithMap,
const bool collisionDebug,
const optional<CollisionTileBoundaries>& avoidEdges,
const optional<std::function<bool(const IndexedSubfeature&)>> collisionGroupPredicate) {
const auto tileUnitAnchorPoint = symbol.anchorPoint;
const auto projectedAnchor = projectAnchor(posMatrix, tileUnitAnchorPoint);
const float fontScale = fontSize / 24;
const float lineOffsetX = symbol.lineOffset[0] * fontSize;
const float lineOffsetY = symbol.lineOffset[1] * fontSize;
const auto labelPlaneAnchorPoint = project(tileUnitAnchorPoint, labelPlaneMatrix).first;
const auto firstAndLastGlyph = placeFirstAndLastGlyph(
fontScale,
lineOffsetX,
lineOffsetY,
/*flip*/ false,
labelPlaneAnchorPoint,
tileUnitAnchorPoint,
symbol,
labelPlaneMatrix,
/*return tile distance*/ true);
bool collisionDetected = false;
bool inGrid = false;
bool entirelyOffscreen = true;
const auto tileToViewport = projectedAnchor.first * textPixelRatio;
// pixelsToTileUnits is used for translating line geometry to tile units
// ... so we care about 'scale' but not 'perspectiveRatio'
// equivalent to pixel_to_tile_units
const auto pixelsToTileUnits = 1 / (textPixelRatio * scale);
float firstTileDistance = 0, lastTileDistance = 0;
if (firstAndLastGlyph) {
firstTileDistance = approximateTileDistance(*(firstAndLastGlyph->first.tileDistance), firstAndLastGlyph->first.angle, pixelsToTileUnits, projectedAnchor.second, pitchWithMap);
lastTileDistance = approximateTileDistance(*(firstAndLastGlyph->second.tileDistance), firstAndLastGlyph->second.angle, pixelsToTileUnits, projectedAnchor.second, pitchWithMap);
}
bool atLeastOneCirclePlaced = false;
for (size_t i = 0; i < feature.boxes.size(); i++) {
CollisionBox& circle = feature.boxes[i];
const float boxSignedDistanceFromAnchor = circle.signedDistanceFromAnchor;
if (!firstAndLastGlyph ||
(boxSignedDistanceFromAnchor < -firstTileDistance) ||
(boxSignedDistanceFromAnchor > lastTileDistance)) {
// The label either doesn't fit on its line or we
// don't need to use this circle because the label
// doesn't extend this far. Either way, mark the circle unused.
circle.used = false;
continue;
}
const auto projectedPoint = projectPoint(posMatrix, circle.anchor);
const float tileUnitRadius = (circle.x2 - circle.x1) / 2;
const float radius = tileUnitRadius * tileToViewport;
if (atLeastOneCirclePlaced) {
const CollisionBox& previousCircle = feature.boxes[i - 1];
const float dx = projectedPoint.x - previousCircle.px;
const float dy = projectedPoint.y - previousCircle.py;
// The circle edges touch when the distance between their centers is 2x the radius
// When the distance is 1x the radius, they're doubled up, and we could remove
// every other circle while keeping them all in touch.
// We actually start removing circles when the distance is √2x the radius:
// thinning the number of circles as much as possible is a major performance win,
// and the small gaps introduced don't make a very noticeable difference.
const bool placedTooDensely = radius * radius * 2 > dx * dx + dy * dy;
if (placedTooDensely) {
const bool atLeastOneMoreCircle = (i + 1) < feature.boxes.size();
if (atLeastOneMoreCircle) {
const CollisionBox& nextCircle = feature.boxes[i + 1];
const float nextBoxDistanceFromAnchor = nextCircle.signedDistanceFromAnchor;
if ((nextBoxDistanceFromAnchor > -firstTileDistance) &&
(nextBoxDistanceFromAnchor < lastTileDistance)) {
// Hide significantly overlapping circles, unless this is the last one we can
// use, in which case we want to keep it in place even if it's tightly packed
// with the one before it.
circle.used = false;
continue;
}
}
}
}
atLeastOneCirclePlaced = true;
circle.px1 = projectedPoint.x - radius;
circle.px2 = projectedPoint.x + radius;
circle.py1 = projectedPoint.y - radius;
circle.py2 = projectedPoint.y + radius;
circle.used = true;
circle.px = projectedPoint.x;
circle.py = projectedPoint.y;
circle.radius = radius;
entirelyOffscreen &= isOffscreen(circle);
inGrid |= isInsideGrid(circle);
if ((avoidEdges && !isInsideTile(circle, *avoidEdges)) ||
(!allowOverlap && collisionGrid.hitTest({{circle.px, circle.py}, circle.radius}, collisionGroupPredicate))) {
if (!collisionDebug) {
return {false, false};
} else {
// Don't early exit if we're showing the debug circles because we still want to calculate
// which circles are in use
collisionDetected = true;
}
}
}
return {!collisionDetected && firstAndLastGlyph && inGrid, entirelyOffscreen};
}
void CollisionIndex::insertFeature(CollisionFeature& feature, bool ignorePlacement, uint32_t bucketInstanceId, uint16_t collisionGroupId) {
if (feature.alongLine) {
for (auto& circle : feature.boxes) {
if (!circle.used) {
continue;
}
if (ignorePlacement) {
ignoredGrid.insert(
IndexedSubfeature(feature.indexedFeature, bucketInstanceId, collisionGroupId),
{{ circle.px, circle.py }, circle.radius}
);
} else {
collisionGrid.insert(
IndexedSubfeature(feature.indexedFeature, bucketInstanceId, collisionGroupId),
{{ circle.px, circle.py }, circle.radius}
);
}
}
} else {
assert(feature.boxes.size() == 1);
auto& box = feature.boxes[0];
if (ignorePlacement) {
ignoredGrid.insert(
IndexedSubfeature(feature.indexedFeature, bucketInstanceId, collisionGroupId),
{{ box.px1, box.py1 }, { box.px2, box.py2 }}
);
} else {
collisionGrid.insert(
IndexedSubfeature(feature.indexedFeature, bucketInstanceId, collisionGroupId),
{{ box.px1, box.py1 }, { box.px2, box.py2 }}
);
}
}
}
bool polygonIntersectsBox(const LineString<float>& polygon, const GridIndex<IndexedSubfeature>::BBox& bbox) {
// This is just a wrapper that allows us to use the integer-based util::polygonIntersectsPolygon
// Conversion limits our query accuracy to single-pixel resolution
GeometryCoordinates integerPolygon;
for (const auto& point : polygon) {
integerPolygon.push_back(convertPoint<int16_t>(point));
}
int16_t minX1 = bbox.min.x;
int16_t maxY1 = bbox.max.y;
int16_t minY1 = bbox.min.y;
int16_t maxX1 = bbox.max.x;
auto bboxPoints = GeometryCoordinates {
{ minX1, minY1 }, { maxX1, minY1 }, { maxX1, maxY1 }, { minX1, maxY1 }
};
return util::polygonIntersectsPolygon(integerPolygon, bboxPoints);
}
std::unordered_map<uint32_t, std::vector<IndexedSubfeature>> CollisionIndex::queryRenderedSymbols(const ScreenLineString& queryGeometry) const {
std::unordered_map<uint32_t, std::vector<IndexedSubfeature>> result;
if (queryGeometry.empty() || (collisionGrid.empty() && ignoredGrid.empty())) {
return result;
}
LineString<float> gridQuery;
for (const auto& point : queryGeometry) {
gridQuery.emplace_back(point.x + viewportPadding, point.y + viewportPadding);
}
auto envelope = mapbox::geometry::envelope(gridQuery);
using QueryResult = std::pair<IndexedSubfeature, GridIndex<IndexedSubfeature>::BBox>;
std::vector<QueryResult> features = collisionGrid.queryWithBoxes(envelope);
std::vector<QueryResult> ignoredFeatures = ignoredGrid.queryWithBoxes(envelope);
features.insert(features.end(), ignoredFeatures.begin(), ignoredFeatures.end());
std::unordered_map<uint32_t, std::unordered_set<size_t>> seenBuckets;
for (auto& queryResult : features) {
auto& feature = queryResult.first;
auto& bbox = queryResult.second;
// Skip already seen features.
auto& seenFeatures = seenBuckets[feature.bucketInstanceId];
if (seenFeatures.find(feature.index) != seenFeatures.end())
continue;
if (!polygonIntersectsBox(gridQuery, bbox)) {
continue;
}
seenFeatures.insert(feature.index);
result[feature.bucketInstanceId].push_back(feature);
}
return result;
}
std::pair<float,float> CollisionIndex::projectAnchor(const mat4& posMatrix, const Point<float>& point) const {
vec4 p = {{ point.x, point.y, 0, 1 }};
matrix::transformMat4(p, p, posMatrix);
return std::make_pair(
0.5 + 0.5 * (transformState.getCameraToCenterDistance() / p[3]),
p[3]
);
}
std::pair<Point<float>,float> CollisionIndex::projectAndGetPerspectiveRatio(const mat4& posMatrix, const Point<float>& point) const {
vec4 p = {{ point.x, point.y, 0, 1 }};
matrix::transformMat4(p, p, posMatrix);
auto offset = transformState.getCenterOffset();
auto size = transformState.getSize();
return std::make_pair(
Point<float>(
(((p[0] / p[3] + 1) / 2) * size.width) + viewportPadding + offset.x,
(((-p[1] / p[3] + 1) / 2) * size.height) + viewportPadding + offset.y
),
// See perspective ratio comment in symbol_sdf.vertex
// We're doing collision detection in viewport space so we need
// to scale down boxes in the distance
0.5 + 0.5 * transformState.getCameraToCenterDistance() / p[3]
);
}
Point<float> CollisionIndex::projectPoint(const mat4& posMatrix, const Point<float>& point) const {
vec4 p = {{ point.x, point.y, 0, 1 }};
matrix::transformMat4(p, p, posMatrix);
auto offset = transformState.getCenterOffset();
auto size = transformState.getSize();
return Point<float> {
static_cast<float>((((p[0] / p[3] + 1) / 2) * size.width) + viewportPadding + offset.x),
static_cast<float>((((-p[1] / p[3] + 1) / 2) * size.height) + viewportPadding + offset.y) };
}
} // namespace mbgl