Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 | 1x 944x 944x 944x 944x 944x 944x 944x 944x 944x 1x 1x 108x 1252x 1252x 1252x 1252x 1252x 1252x 1252x 1x 308x 308x 308x 308x 308x 308x 308x 1x 1x 1x 90x 78x 90x 90x 90x 90x 90x 90x 90x 78x 78x 78x 78x 78x 44859x 78x 78x 1x 1x 1560x 1560x 1560x 1560x 42278x 42278x 42278x 42278x 1x 106x 106x 17x 89x 89x 85x 85x 4x 16x 90x 90x 90x 85x 85x 85x 85x 85x 90x 85x 5x 85x 85x 85x 85x 85x 85x 85x 85x 77x 77x 85x 47333x 47333x 47333x 47333x 47333x 47333x 93x 47333x 42278x 85x 77x 308x 77x 85x 1x 141999x 141999x 112929x 29070x 29070x 29070x 29070x 29070x 77x 77x 77x 77x 77x 308x 308x 77x 77x 77x 77x 77x 77x 308x 77x 77x | import AxisAlignedBoundingBox from "./AxisAlignedBoundingBox.js";
import Cartesian3 from "./Cartesian3.js";
import defined from "./defined.js";
import IntersectionTests from "./IntersectionTests.js";
import Matrix4 from "./Matrix4.js";
import Ray from "./Ray.js";
import TaskProcessor from "./TaskProcessor.js";
import Cartographic from "./Cartographic.js";
import SceneMode from "../Scene/SceneMode.js";
import Interval from "./Interval.js";
import Check from "./Check.js";
import DeveloperError from "./DeveloperError.js";
// Terrain picker can be 4 levels deep (0-3)
const MAXIMUM_TERRAIN_PICKER_LEVEL = 3;
/**
* Creates an object that handles arbitrary ray intersections with a terrain mesh using a spatial acceleration structure.
*
* @alias TerrainPicker
* @constructor
*
* @param {Float32Array} vertices The terrain mesh's vertex buffer.
* @param {Uint8Array|Uint16Array|Uint32Array} indices The terrain mesh's index buffer.
* @param {TerrainEncoding} encoding The terrain mesh's vertex encoding.
*
* @private
*/
function TerrainPicker(vertices, indices, encoding) {
//>>includeStart('debug', pragmas.debug);
Check.defined("vertices", vertices);
Check.defined("indices", indices);
Check.defined("encoding", encoding);
//>>includeEnd('debug');
/**
* The terrain mesh's vertex buffer.
* @type {Float32Array}
*/
this._vertices = vertices;
/**
* The terrain mesh's index buffer.
* @type {Uint32Array}
*/
this._indices = indices;
/**
* The terrain mesh's vertex encoding.
* @type {TerrainEncoding}
*/
this._encoding = encoding;
/**
* The inverse of the terrain mesh tile's transform from world space to local space.
* @type {Matrix4}
*/
this._inverseTransform = new Matrix4(); // Compute as-needed on rebuild
/**
* Whether or not to reset this terrain mesh's picker on the next ray intersection.
* @type {Boolean}
*/
this._needsRebuild = true;
/**
* The root node of the terrain picker's quadtree.
* @type {TerrainPickerNode}
*/
this._rootNode = new TerrainPickerNode();
}
const incrementallyBuildTerrainPickerTaskProcessor = new TaskProcessor(
"incrementallyBuildTerrainPicker",
);
Object.defineProperties(TerrainPicker.prototype, {
/**
* Indicates whether the terrain picker needs to be rebuilt due to changes in the underlying terrain mesh's vertices or indices.
* @type {boolean}
*/
needsRebuild: {
get: function () {
return this._needsRebuild;
},
set: function (value) {
this._needsRebuild = value;
},
},
});
/**
* A node in the terrain picker quadtree.
* @constructor
* @private
*/
function TerrainPickerNode() {
/**
* The tree-space x-coordinate of this node.
* @type {Number}
*/
this.x = 0;
/**
* The tree-space y-coordinate of this node.
* @type {Number}
*/
this.y = 0;
/**
* The level of this node in the quadtree.
* @type {Number}
*/
this.level = 0;
/**
* The axis-aligned bounding box of this node (in the tree's local space).
* @type {AxisAlignedBoundingBox}
*/
this.aabb = createAABBForNode(this.x, this.y, this.level);
/**
* The indices of the triangles that intersect this node.
* @type {Uint32Array}
*/
this.intersectingTriangles = new Uint32Array(0);
/**
* The child terrain picker nodes of this node.
* @type {TerrainPickerNode[]}
*/
this.children = [];
/**
* Whether or not this node is currently building its children on a worker.
* @type {Boolean}
*/
this.buildingChildren = false;
}
/**
* Adds a child node to this node.
*
* @param {number} childIdx The index of the child to add (0-3).
* @memberof TerrainPickerNode
*/
TerrainPickerNode.prototype.addChild = function (childIdx) {
//>>includeStart('debug', pragmas.debug);
Iif (childIdx < 0 || childIdx > 3) {
throw new DeveloperError(
"TerrainPickerNode child index must be between 0 and 3, inclusive.",
);
}
//>>includeEnd('debug');
const childNode = new TerrainPickerNode();
// Use bitwise operations to get child x,y from child index and parent x,y
childNode.x = this.x * 2 + (childIdx & 1);
childNode.y = this.y * 2 + ((childIdx >> 1) & 1);
childNode.level = this.level + 1;
childNode.aabb = createAABBForNode(childNode.x, childNode.y, childNode.level);
this.children[childIdx] = childNode;
};
const scratchTransformedRay = new Ray();
const scratchTrianglePoints = [
new Cartesian3(),
new Cartesian3(),
new Cartesian3(),
];
/**
* Determines the point on the mesh where the given ray intersects.
* @param {Ray} ray The ray to test.
* @param {Matrix4} tileTransform The terrain mesh tile's transform from local space to world space.
* @param {Boolean} cullBackFaces Whether to consider back-facing triangles as intersections.
* @param {SceneMode} mode The scene mode (2D/3D/Columbus View).
* @param {MapProjection} projection The map projection.
* @returns {Cartesian3 | undefined} result The intersection point, or undefined if there is no intersection.
* @memberof TerrainPicker
* @private
*/
TerrainPicker.prototype.rayIntersect = function (
ray,
tileTransform,
cullBackFaces,
mode,
projection,
) {
// Lazily (re)create the terrain picker
if (this._needsRebuild) {
reset(this, tileTransform);
}
const invTransform = this._inverseTransform;
const transformedRay = scratchTransformedRay;
transformedRay.origin = Matrix4.multiplyByPoint(
invTransform,
ray.origin,
transformedRay.origin,
);
transformedRay.direction = Matrix4.multiplyByPointAsVector(
invTransform,
ray.direction,
transformedRay.direction,
);
const intersections = [];
getNodesIntersectingRay(this._rootNode, transformedRay, intersections);
return findClosestPointInClosestNode(
this,
intersections,
ray,
cullBackFaces,
mode,
projection,
);
};
/**
* Resets the terrain picker's quadtree structure to just the root node. Done whenever the underlying terrain mesh changes.
* @param terrainPicker The terrain picker to reset.
* @private
*/
function reset(terrainPicker, tileTransform) {
// PERFORMANCE_IDEA: warm-start the terrain picker by building a level on a worker.
// This currently isn't feasible because you can only copy the vertex buffer to a worker (slow) or transfer ownership (can't do picking on main thread in meantime).
// SharedArrayBuffers could be used, but most environments do not support them.
Matrix4.inverse(tileTransform, terrainPicker._inverseTransform);
terrainPicker._needsRebuild = false;
const triangleCount = terrainPicker._indices.length / 3;
const intersectingTriangles = new Uint32Array(triangleCount);
for (let i = 0; i < triangleCount; ++i) {
intersectingTriangles[i] = i;
}
terrainPicker._rootNode.intersectingTriangles = intersectingTriangles;
terrainPicker._rootNode.children.length = 0;
}
const scratchAABBMin = new Cartesian3();
const scratchAABBMax = new Cartesian3();
/**
* Creates an axis-aligned bounding box for a quadtree node at the given tree-space coordinates and level.
* This AABB is in the tree's local space (where the root node of the tree is a unit cube in its own local space).
*
* @param {number} x The x coordinate of the node.
* @param {number} y The y coordinate of the node.
* @param {number} level The level of the node.
* @returns {AxisAlignedBoundingBox} The axis-aligned bounding box for the node.
*/
function createAABBForNode(x, y, level) {
const sizeAtLevel = 1.0 / Math.pow(2, level);
const aabbMin = Cartesian3.fromElements(
x * sizeAtLevel - 0.5,
y * sizeAtLevel - 0.5,
-0.5,
scratchAABBMin,
);
const aabbMax = Cartesian3.fromElements(
(x + 1) * sizeAtLevel - 0.5,
(y + 1) * sizeAtLevel - 0.5,
0.5,
scratchAABBMax,
);
return AxisAlignedBoundingBox.fromCorners(aabbMin, aabbMax);
}
/**
* Packs triangle vertex positions and index into provided buffers, for the worker to process.
* (The worker does tests to organize triangles into child nodes of the quadtree.)
* @param {Float32Array} trianglePositionsBuffer The buffer to pack triangle vertex positions into.
* @param {Uint32Array} triangleIndicesBuffer The buffer to pack triangle indices into.
* @param {Cartesian3[]} trianglePositions The triangle's vertex positions.
* @param {number} triangleIndex The triangle's index in the overall tile's index buffer.
* @param {number} bufferIndex The index to use to pack into the buffers.
* @private
*/
function packTriangleBuffers(
trianglePositionsBuffer,
triangleIndicesBuffer,
trianglePositions,
triangleIndex,
bufferIndex,
) {
Cartesian3.pack(
trianglePositions[0],
trianglePositionsBuffer,
9 * bufferIndex,
);
Cartesian3.pack(
trianglePositions[1],
trianglePositionsBuffer,
9 * bufferIndex + 3,
);
Cartesian3.pack(
trianglePositions[2],
trianglePositionsBuffer,
9 * bufferIndex + 6,
);
triangleIndicesBuffer[bufferIndex] = triangleIndex;
}
/**
* @typedef {Object} IntersectingNode
* @property {TerrainPickerNode} node - The intersecting quadtree node.
* @property {Interval} interval - The interval along the ray where the intersection occurs.
* @private
*/
const scratchInterval = new Interval();
/**
* Recursively gathers all nodes in the quadtree that intersect the ray.
*
* @param {TerrainPickerNode} currentNode The current node being tested.
* @param {Ray} ray The ray to test.
* @param {IntersectingNode[]} intersectingNodes The array to store intersecting nodes in.
* @private
*/
function getNodesIntersectingRay(currentNode, ray, intersectingNodes) {
const interval = IntersectionTests.rayAxisAlignedBoundingBox(
ray,
currentNode.aabb,
scratchInterval,
);
if (!defined(interval)) {
return;
}
const isLeaf = !currentNode.children.length || currentNode.buildingChildren;
if (isLeaf) {
intersectingNodes.push({
node: currentNode,
interval: new Interval(interval.start, interval.stop),
});
return;
}
for (let i = 0; i < currentNode.children.length; i++) {
getNodesIntersectingRay(currentNode.children[i], ray, intersectingNodes);
}
}
/**
* Finds the closest intersecting node along the ray, in world space, and the closest point in that node,
* by testing all triangles in the closest node against the ray.
*
* @param {TerrainPicker} terrainPicker The terrain picker.
* @param {IntersectingNode[]} intersections The nodes that intersect the ray, along with the intersection intervals along said ray.
* @param {Ray} ray The ray to test.
* @param {boolean} cullBackFaces Whether to cull back faces.
* @param {SceneMode} mode The scene mode (2D/3D/Columbus View).
* @param {MapProjection} projection The map projection.
* @returns The closest point in world space, or undefined if no intersection.
* @private
*/
function findClosestPointInClosestNode(
terrainPicker,
intersections,
ray,
cullBackFaces,
mode,
projection,
) {
const sortedIntersections = intersections.sort(function (a, b) {
return a.interval.start - b.interval.start;
});
let minT = Number.MAX_VALUE;
for (let i = 0; i < sortedIntersections.length; i++) {
const intersection = sortedIntersections[i];
const intersectionResult = getClosestTriangleInNode(
terrainPicker,
ray,
intersection.node,
cullBackFaces,
mode,
projection,
);
minT = Math.min(intersectionResult, minT);
Eif (minT !== Number.MAX_VALUE) {
break;
}
}
if (minT !== Number.MAX_VALUE) {
return Ray.getPoint(ray, minT);
}
return undefined;
}
/**
* Test all triangles in the given node against the ray, returning the closest intersection t value along the ray.
* Additionally, collect the triangles' positions and indices along the way to launch worker process that uses them to build out child nodes.
*
* @param {TerrainPicker} terrainPicker The terrain picker.
* @param {Ray} ray The ray to test.
* @param {TerrainPickerNode} node The node to test.
* @param {boolean} cullBackFaces Whether to cull back faces.
* @param {SceneMode} mode The scene mode (2D/3D/Columbus View).
* @param {MapProjection} projection The map projection.
* @returns {number} The closest intersection t value along the ray, or Number.MAX_VALUE if no intersection.
* @private
*/
function getClosestTriangleInNode(
terrainPicker,
ray,
node,
cullBackFaces,
mode,
projection,
) {
let result = Number.MAX_VALUE;
const encoding = terrainPicker._encoding;
const indices = terrainPicker._indices;
const vertices = terrainPicker._vertices;
const triangleCount = node.intersectingTriangles.length;
const isMaxLevel = node.level >= MAXIMUM_TERRAIN_PICKER_LEVEL;
const shouldBuildChildren = !isMaxLevel && !node.buildingChildren;
let trianglePositions;
let triangleIndices;
if (shouldBuildChildren) {
// If the tree can be built deeper, prepare buffers to store triangle data for child nodes
trianglePositions = new Float32Array(triangleCount * 9); // 3 vertices per triangle * 3 floats per vertex
triangleIndices = new Uint32Array(triangleCount);
}
for (let i = 0; i < triangleCount; i++) {
const triIndex = node.intersectingTriangles[i];
const v0 = getVertexPosition(
encoding,
mode,
projection,
vertices,
indices[3 * triIndex],
scratchTrianglePoints[0],
);
const v1 = getVertexPosition(
encoding,
mode,
projection,
vertices,
indices[3 * triIndex + 1],
scratchTrianglePoints[1],
);
const v2 = getVertexPosition(
encoding,
mode,
projection,
vertices,
indices[3 * triIndex + 2],
scratchTrianglePoints[2],
);
const triT = IntersectionTests.rayTriangleParametric(
ray,
v0,
v1,
v2,
cullBackFaces,
);
if (defined(triT) && triT < result && triT >= 0) {
result = triT;
}
if (shouldBuildChildren) {
packTriangleBuffers(
trianglePositions,
triangleIndices,
scratchTrianglePoints,
triIndex,
i,
);
}
}
if (shouldBuildChildren) {
for (let childIdx = 0; childIdx < 4; childIdx++) {
node.addChild(childIdx);
}
addTrianglesToChildrenNodes(
terrainPicker._inverseTransform,
node,
triangleIndices,
trianglePositions,
);
}
return result;
}
const scratchCartographic = new Cartographic();
/**
* Gets a vertex position from the buffer, taking into account the exaggeration and scene mode of the terrain.
*
* @param {TerrainEncoding} encoding The terrain encoding.
* @param {SceneMode} mode The scene mode (2D/3D/Columbus View).
* @param {MapProjection} projection The map projection.
* @param {Float32Array} vertices The vertex buffer of the terrain mesh.
* @param {Number} index The index of the vertex to get.
* @param {Cartesian3} result The decoded, exaggerated, and possibly projected vertex position.
* @returns {Cartesian3} The result vertex position.
* @private
*/
function getVertexPosition(
encoding,
mode,
projection,
vertices,
index,
result,
) {
let position = encoding.getExaggeratedPosition(vertices, index, result);
if (mode === SceneMode.SCENE3D) {
return position;
}
const ellipsoid = projection.ellipsoid;
const positionCartographic = ellipsoid.cartesianToCartographic(
position,
scratchCartographic,
);
position = projection.project(positionCartographic, result);
// Swizzle because coordinate basis are different in 2D/Columbus View
position = Cartesian3.fromElements(
position.z,
position.x,
position.y,
result,
);
return position;
}
/**
* Adds triangles to the child nodes of the given node by launching a worker process to do AABB-triangle testing.
*
* @param {Matrix4} inverseTransform
* @param {TerrainNode} node
* @param {Uint32Array} triangleIndices
* @param {Float32Array} trianglePositions
* @returns {Promise<void>} A promise that resolves when the triangles have been added to the child nodes.
* @private
*/
async function addTrianglesToChildrenNodes(
inverseTransform,
node,
triangleIndices,
trianglePositions,
) {
node.buildingChildren = true;
// Prepare data to be sent to a worker
const inverseTransformPacked = new Float64Array(16);
Matrix4.pack(inverseTransform, inverseTransformPacked, 0);
const aabbArray = new Float64Array(6 * 4); // 6 elements per AABB, 4 children
for (let i = 0; i < 4; i++) {
Cartesian3.pack(node.children[i].aabb.minimum, aabbArray, i * 6);
Cartesian3.pack(node.children[i].aabb.maximum, aabbArray, i * 6 + 3);
}
const parameters = {
aabbs: aabbArray,
inverseTransform: inverseTransformPacked,
triangleIndices: triangleIndices,
trianglePositions: trianglePositions,
};
const transferableObjects = [
aabbArray.buffer,
inverseTransformPacked.buffer,
triangleIndices.buffer,
trianglePositions.buffer,
];
const incrementallyBuildTerrainPickerPromise =
incrementallyBuildTerrainPickerTaskProcessor.scheduleTask(
parameters,
transferableObjects,
);
Iif (!defined(incrementallyBuildTerrainPickerPromise)) {
// Failed to schedule task, retry on next pick
node.buildingChildren = false;
return;
}
// After worker completes, it transfers back a buffer of intersecting triangles for each child node
// Assign these to the child nodes
const result = await incrementallyBuildTerrainPickerPromise;
result.intersectingTrianglesArrays.forEach((buffer, index) => {
node.children[index].intersectingTriangles = new Uint32Array(buffer);
});
// The node's triangles have been distributed to its children
node.intersectingTriangles = new Uint32Array(0);
node.buildingChildren = false;
}
export default TerrainPicker;
|