Skip to content

Commit 093702b

Browse files
jakra-mbgithub-actions[bot]
authored andcommitted
Raycast the picking mesh in point queries of 3D landmarks
GitOrigin-RevId: b15f18c0b82afb55e8464dc7a27648fd198b2995
1 parent 83a6f4c commit 093702b

10 files changed

Lines changed: 382 additions & 5 deletions

File tree

‎3d-style/source/model_bvh.ts‎

Lines changed: 132 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,72 @@ function triangleAABBIntersect(
107107
return true;
108108
}
109109

110-
// Reused across findHighestPoint calls; calls are synchronous so a single shared array is safe.
110+
// Distance at which a ray enters node i's box (0 if the origin is inside), or -1 if the ray misses the box
111+
// within maxDistance
112+
function nodeRayEntry(
113+
nodeMin: Float32Array, nodeMax: Float32Array, i: number,
114+
origin: ArrayLike<number>, dir: ArrayLike<number>, maxDistance: number
115+
): number {
116+
const o = i * 3;
117+
let tMin = 0;
118+
let tMax = maxDistance;
119+
for (let axis = 0; axis < 3; axis++) {
120+
const min = nodeMin[o + axis]!;
121+
const max = nodeMax[o + axis]!;
122+
const p = origin[axis]!;
123+
const d = dir[axis]!;
124+
if (Math.abs(d) < 1e-12) {
125+
// parallel to this slab
126+
if (p < min || p > max) return -1;
127+
continue;
128+
}
129+
let t1 = (min - p) / d;
130+
let t2 = (max - p) / d;
131+
if (t1 > t2) {
132+
const tmp = t1;
133+
t1 = t2;
134+
t2 = tmp;
135+
}
136+
if (t1 > tMin) tMin = t1;
137+
if (t2 < tMax) tMax = t2;
138+
if (tMin > tMax) return -1;
139+
}
140+
return tMin;
141+
}
142+
143+
// Möller–Trumbore ray-triangle intersection, for both triangle windings.
144+
// Returns the distance along the ray, or -1 if the ray misses the triangle or hits it behind the origin.
145+
function rayTriangleDistance(
146+
origin: ArrayLike<number>, dir: ArrayLike<number>,
147+
vertices: Float32Array, i0: number, i1: number, i2: number
148+
): number {
149+
const v0x = vertices[i0]!, v0y = vertices[i0 + 1]!, v0z = vertices[i0 + 2]!;
150+
const e1x = vertices[i1]! - v0x, e1y = vertices[i1 + 1]! - v0y, e1z = vertices[i1 + 2]! - v0z;
151+
const e2x = vertices[i2]! - v0x, e2y = vertices[i2 + 1]! - v0y, e2z = vertices[i2 + 2]! - v0z;
152+
const dx = dir[0]!, dy = dir[1]!, dz = dir[2]!;
153+
154+
const px = dy * e2z - dz * e2y;
155+
const py = dz * e2x - dx * e2z;
156+
const pz = dx * e2y - dy * e2x;
157+
const det = e1x * px + e1y * py + e1z * pz;
158+
if (det === 0) return -1; // ray is parallel to the triangle plane
159+
const invDet = 1 / det;
160+
161+
const sx = origin[0]! - v0x, sy = origin[1]! - v0y, sz = origin[2]! - v0z;
162+
const u = (sx * px + sy * py + sz * pz) * invDet;
163+
if (u < 0 || u > 1) return -1;
164+
165+
const qx = sy * e1z - sz * e1y;
166+
const qy = sz * e1x - sx * e1z;
167+
const qz = sx * e1y - sy * e1x;
168+
const v = (dx * qx + dy * qy + dz * qz) * invDet;
169+
if (v < 0 || u + v > 1) return -1;
170+
171+
const t = (e2x * qx + e2y * qy + e2z * qz) * invDet;
172+
return t >= 0 ? t : -1;
173+
}
174+
175+
// Reused across findHighestPoint and raycast calls; calls are synchronous so a single shared array is safe.
111176
const findHighestPointStack: number[] = [];
112177

113178
export class ModelBVH {
@@ -170,13 +235,13 @@ export class ModelBVH {
170235

171236
findHighestPoint(aabbMin: [number, number, number], aabbMax: [number, number, number]): number | null {
172237
const nodeData = this._nodeData;
173-
if (!nodeData) return null;
238+
const vertices = this._vertices;
239+
if (!nodeData || !vertices) return null;
174240
const nodeMin = this._nodeMin;
175241
const nodeMax = this._nodeMax;
176242
if (!nodeOverlap(nodeMin, nodeMax, 0, aabbMin, aabbMax)) return null;
177243

178244
const indices = this._indices;
179-
const vertices = this._vertices;
180245
const stack = findHighestPointStack;
181246
stack.length = 0;
182247
stack.push(0);
@@ -230,6 +295,70 @@ export class ModelBVH {
230295

231296
return highest >= 0 ? highest : null;
232297
}
298+
299+
/**
300+
* Finds the closest triangle hit along a ray, in the BVH's model space.
301+
* Hits behind the origin don't count. Returns null if the BVH or its vertices are missing.
302+
* @param origin Start of the ray.
303+
* @param dir Direction of the ray. The result is in multiples of its length, so pass it normalized to get a distance.
304+
* @param maxDistance Hits at or beyond this distance are ignored.
305+
* @returns The distance to the closest hit, or null if there is no hit.
306+
*/
307+
raycast(origin: ArrayLike<number>, dir: ArrayLike<number>, maxDistance: number = Infinity): number | null {
308+
const nodeData = this._nodeData;
309+
const vertices = this._vertices;
310+
if (!nodeData || !vertices) return null;
311+
const nodeMin = this._nodeMin;
312+
const nodeMax = this._nodeMax;
313+
const indices = this._indices;
314+
315+
const stack = findHighestPointStack;
316+
stack.length = 0;
317+
stack.push(0);
318+
let closest = maxDistance;
319+
320+
while (stack.length > 0) {
321+
const nodeIdx = stack.pop()!;
322+
// Re-test on pop, since a hit found in the meantime may make this node too far away
323+
if (nodeRayEntry(nodeMin, nodeMax, nodeIdx, origin, dir, closest) < 0) continue;
324+
325+
const backIdx = nodeData[nodeIdx * 3]!;
326+
327+
if (backIdx === LEAF) {
328+
const indexCount = nodeData[nodeIdx * 3 + 1]!;
329+
const indexOffset = nodeData[nodeIdx * 3 + 2]!;
330+
for (let tri = 0; tri < indexCount; tri += 3) {
331+
const t = rayTriangleDistance(origin, dir, vertices,
332+
indices[indexOffset + tri]! * 3,
333+
indices[indexOffset + tri + 1]! * 3,
334+
indices[indexOffset + tri + 2]! * 3);
335+
if (t >= 0 && t < closest) closest = t;
336+
}
337+
continue;
338+
}
339+
340+
const frontIdx = nodeIdx + 1;
341+
const frontEntry = nodeRayEntry(nodeMin, nodeMax, frontIdx, origin, dir, closest);
342+
const backEntry = nodeRayEntry(nodeMin, nodeMax, backIdx, origin, dir, closest);
343+
344+
// Push the farther child first, so the nearer one is processed first and can prune the other
345+
if (frontEntry >= 0 && backEntry >= 0) {
346+
if (frontEntry < backEntry) {
347+
stack.push(backIdx);
348+
stack.push(frontIdx);
349+
} else {
350+
stack.push(frontIdx);
351+
stack.push(backIdx);
352+
}
353+
} else if (frontEntry >= 0) {
354+
stack.push(frontIdx);
355+
} else if (backEntry >= 0) {
356+
stack.push(backIdx);
357+
}
358+
}
359+
360+
return closest < maxDistance ? closest : null;
361+
}
233362
}
234363

235364
register(ModelBVH, 'ModelBVH');

‎3d-style/style/style_layer/model_layer_query.ts‎

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import {mat4} from 'gl-matrix';
1+
import {mat4, vec3} from 'gl-matrix';
22
import {calculateModelMatrix, tiledModelTileTranslation} from '../../data/model';
33
import LngLat from '../../../src/geo/lng_lat';
44
import {latFromMercatorY, lngFromMercatorX, tileToMeter} from '../../../src/geo/mercator_coordinate';
@@ -216,7 +216,32 @@ export function loadMatchingModelFeature(bucket: Tiled3dModelBucket, featureInde
216216
}
217217
};
218218

219-
checkNode(node);
219+
// Bounding boxes are only a coarse test. For point queries, test the actual geometry through the BVH picking
220+
// mesh, if the model has one. Tiled models keep their meshes on root nodes, so only the root node is tested.
221+
const bvh = node.meshBVH;
222+
if (screenQuery.isPointQuery() && bvh) {
223+
const worldViewProjection = mat4.multiply([], modelMatrix, node.globalMatrix);
224+
mat4.multiply(worldViewProjection, transform.expandedFarZProjMatrix, worldViewProjection);
225+
const invWorldViewProjection = mat4.invert(new Float64Array(16), worldViewProjection);
226+
if (!invWorldViewProjection) return;
227+
228+
// Unproject the point on the near and far plane, to get the ray directly in the BVH's model space
229+
const point = screenQuery.screenBounds[0]!;
230+
const ndcX = point.x / transform.width * 2 - 1;
231+
const ndcY = 1 - point.y / transform.height * 2;
232+
const origin = vec3.transformMat4([], [ndcX, ndcY, -1], invWorldViewProjection);
233+
const far = vec3.transformMat4([], [ndcX, ndcY, 1], invWorldViewProjection);
234+
const dir = vec3.normalize(far, vec3.subtract(far, far, origin));
235+
236+
const distance = bvh.raycast(origin, dir);
237+
if (distance === null) return;
238+
239+
// Report the depth of the hit point, to sort it correctly against other 3D features
240+
const hit = vec3.scaleAndAdd(dir, origin, dir, distance);
241+
intersectionZ = vec3.transformMat4(hit, hit, worldViewProjection)[2];
242+
} else {
243+
checkNode(node);
244+
}
220245
if (intersectionZ === Number.MAX_VALUE) return;
221246

222247
const position = new LngLat(0, 0);

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
- Fix `model-scale` with an x or y scale other than 1 moving 3D landmarks away from their center.
44
- Fix `queryRenderedFeatures` reporting wrong positions for 3D landmarks, and missing landmarks that use `model-translation`.
5+
- Fix `queryRenderedFeatures` and tap interactions returning 3D landmarks for points in empty space near a building, and in the wrong order when landmarks overlap.
56
- Fix `fill-extrusion-pattern-cross-fade` causing extra shader compilation and not being applied on some tiles with shadows enabled.
67
- Fix fill-extrusion buildings hidden by a `clip` layer still being returned by `queryRenderedFeatures`.
78
- Fix a GPU memory leak in fill-extrusion layers with `fill-extrusion-line-width`.
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
[
2+
{
3+
"type": "Feature",
4+
"state": {},
5+
"geometry": {
6+
"type": "Point",
7+
"coordinates": [
8+
11.557161211967468,
9+
48.17503302957351
10+
]
11+
},
12+
"properties": {
13+
"height": 13.008712768554688
14+
},
15+
"id": "158050570",
16+
"source": "landmarks"
17+
}
18+
]
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
{
2+
"version": 8,
3+
"description": "Point query on a landmark tile with BVH picking meshes. The point is on a building and inside the bounding box of a dome in front of it, but misses the dome mesh, so only the building must be returned.",
4+
"metadata": {
5+
"test": {
6+
"width": 512,
7+
"height": 512,
8+
"queryGeometry": [175, 210]
9+
}
10+
},
11+
"center": [11.5555, 48.1752],
12+
"zoom": 16.2,
13+
"pitch": 65,
14+
"bearing": 150,
15+
"sources": {
16+
"landmarks": {
17+
"type": "batched-model",
18+
"maxzoom": 14,
19+
"tiles": ["local://models/landmark/mbx-lod/{x}-{y}-{z}.glb"]
20+
}
21+
},
22+
"layers": [
23+
{
24+
"id": "landmarks",
25+
"type": "model",
26+
"source": "landmarks",
27+
"minzoom": 14
28+
}
29+
]
30+
}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
[]
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
{
2+
"version": 8,
3+
"description": "Point query on a landmark tile with BVH picking meshes. The point is inside the bounding box of a curved bridge, but next to the bridge deck, so the bridge must not be returned.",
4+
"metadata": {
5+
"test": {
6+
"width": 512,
7+
"height": 512,
8+
"queryGeometry": [220, 300]
9+
}
10+
},
11+
"center": [11.5555, 48.1752],
12+
"zoom": 16.2,
13+
"pitch": 65,
14+
"bearing": 150,
15+
"sources": {
16+
"landmarks": {
17+
"type": "batched-model",
18+
"maxzoom": 14,
19+
"tiles": ["local://models/landmark/mbx-lod/{x}-{y}-{z}.glb"]
20+
}
21+
},
22+
"layers": [
23+
{
24+
"id": "landmarks",
25+
"type": "model",
26+
"source": "landmarks",
27+
"minzoom": 14
28+
}
29+
]
30+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
[
2+
{
3+
"type": "Feature",
4+
"state": {},
5+
"geometry": {
6+
"type": "Point",
7+
"coordinates": [
8+
11.55796955460761,
9+
48.17503302957351
10+
]
11+
},
12+
"properties": {
13+
"height": 13.008712768554688
14+
},
15+
"id": "158050570",
16+
"source": "landmarks"
17+
}
18+
]
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
{
2+
"version": 8,
3+
"description": "Point query on landmarks moved 60 m east with model-translation. The point is on the moved building, where nothing is without the translation, so the query must use the same placement as rendering.",
4+
"metadata": {
5+
"test": {
6+
"width": 512,
7+
"height": 512,
8+
"queryGeometry": [430, 256]
9+
}
10+
},
11+
"center": [11.557161, 48.175033],
12+
"zoom": 17,
13+
"pitch": 0,
14+
"bearing": 0,
15+
"sources": {
16+
"landmarks": {
17+
"type": "batched-model",
18+
"maxzoom": 14,
19+
"tiles": ["local://models/landmark/mbx-lod/{x}-{y}-{z}.glb"]
20+
}
21+
},
22+
"layers": [
23+
{
24+
"id": "landmarks",
25+
"type": "model",
26+
"source": "landmarks",
27+
"minzoom": 14,
28+
"paint": {
29+
"model-translation": [60, 0, 0]
30+
}
31+
}
32+
]
33+
}

0 commit comments

Comments
 (0)