-
Notifications
You must be signed in to change notification settings - Fork 262
Expand file tree
/
Copy pathTilesetHeightQuery.cpp
More file actions
511 lines (437 loc) · 16.6 KB
/
TilesetHeightQuery.cpp
File metadata and controls
511 lines (437 loc) · 16.6 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
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
#include "TilesetHeightQuery.h"
#include "TilesetContentManager.h"
#include <Cesium3DTilesSelection/BoundingVolume.h>
#include <Cesium3DTilesSelection/ITilesetHeightSampler.h>
#include <Cesium3DTilesSelection/SampleHeightResult.h>
#include <Cesium3DTilesSelection/Tile.h>
#include <Cesium3DTilesSelection/TileContent.h>
#include <Cesium3DTilesSelection/TileRefine.h>
#include <CesiumAsync/Promise.h>
#include <CesiumGeometry/BoundingCylinderRegion.h>
#include <CesiumGeometry/IntersectionTests.h>
#include <CesiumGeospatial/BoundingRegion.h>
#include <CesiumGeospatial/BoundingRegionWithLooseFittingHeights.h>
#include <CesiumGeospatial/Cartographic.h>
#include <CesiumGeospatial/Ellipsoid.h>
#include <CesiumGeospatial/GlobeRectangle.h>
#include <CesiumGeospatial/S2CellBoundingVolume.h>
#include <CesiumGltfContent/GltfUtilities.h>
#include <glm/exponential.hpp>
#include <cstddef>
#include <iterator>
#include <list>
#include <optional>
#include <set>
#include <string>
#include <utility>
#include <variant>
#include <vector>
using namespace Cesium3DTilesSelection;
using namespace CesiumGeospatial;
using namespace CesiumGeometry;
using namespace CesiumUtility;
using namespace CesiumAsync;
namespace {
bool boundingVolumeContainsCoordinate(
const BoundingVolume& boundingVolume,
const Ray& ray,
const Cartographic& coordinate,
const Ellipsoid& ellipsoid) {
struct Operation {
const Ray& ray;
const Cartographic& coordinate;
const Ellipsoid& ellipsoid;
bool operator()(const OrientedBoundingBox& boundingBox) noexcept {
std::optional<double> t =
IntersectionTests::rayOBBParametric(ray, boundingBox);
return t && t.value() >= 0;
}
bool operator()(const BoundingRegion& boundingRegion) noexcept {
return boundingRegion.getRectangle().contains(coordinate);
}
bool operator()(const BoundingSphere& boundingSphere) noexcept {
std::optional<double> t =
IntersectionTests::raySphereParametric(ray, boundingSphere);
return t && t.value() >= 0;
}
bool operator()(
const BoundingRegionWithLooseFittingHeights& boundingRegion) noexcept {
return boundingRegion.getBoundingRegion().getRectangle().contains(
coordinate);
}
bool operator()(const S2CellBoundingVolume& s2Cell) noexcept {
return s2Cell.computeBoundingRegion(ellipsoid).getRectangle().contains(
coordinate);
}
bool operator()(const BoundingCylinderRegion& cylinderRegion) noexcept {
std::optional<double> t = IntersectionTests::rayOBBParametric(
ray,
cylinderRegion.toOrientedBoundingBox());
return t && t.value() >= 0;
}
};
return std::visit(Operation{ray, coordinate, ellipsoid}, boundingVolume);
}
// The ray for height queries starts at this fraction of the ellipsoid max
// radius above the ellipsoid surface. If a tileset surface is more than this
// distance above the ellipsoid, it may be missed by height queries.
// 0.007 is chosen to accomodate Olympus Mons, the tallest peak on Mars. 0.007
// is seven-tenths of a percent, or about 44,647 meters for WGS84, well above
// the highest point on Earth.
const double rayOriginHeightFraction = 0.007;
Ray createRay(const Cartographic& position, const Ellipsoid& ellipsoid) {
Cartographic startPosition(
position.longitude,
position.latitude,
ellipsoid.getMaximumRadius() * rayOriginHeightFraction);
return Ray(
ellipsoid.cartographicToCartesian(startPosition),
-ellipsoid.geodeticSurfaceNormal(startPosition));
}
} // namespace
TilesetHeightQuery::TilesetHeightQuery(
const Cartographic& position,
const Ellipsoid& ellipsoid_)
: inputPosition(position),
ray(createRay(position, ellipsoid_)),
ellipsoid(ellipsoid_),
intersection(),
additiveCandidateTiles(),
candidateTiles(),
previousCandidateTiles() {}
Cesium3DTilesSelection::TilesetHeightQuery::~TilesetHeightQuery() = default;
void TilesetHeightQuery::intersectVisibleTile(
Tile* pTile,
std::vector<std::string>& outWarnings) {
TileRenderContent* pRenderContent = pTile->getContent().getRenderContent();
if (!pRenderContent)
return;
auto gltfIntersectResult =
CesiumGltfContent::GltfUtilities::intersectRayGltfModel(
this->ray,
pRenderContent->getModel(),
true,
pTile->getTransform());
if (!gltfIntersectResult.warnings.empty()) {
outWarnings.insert(
outWarnings.end(),
std::make_move_iterator(gltfIntersectResult.warnings.begin()),
std::make_move_iterator(gltfIntersectResult.warnings.end()));
}
// Set ray info to this hit if closer, or the first hit
if (!this->intersection.has_value()) {
this->intersection = std::move(gltfIntersectResult.hit);
} else if (gltfIntersectResult.hit) {
double prevDistSq = this->intersection->rayToWorldPointDistanceSq;
double thisDistSq = gltfIntersectResult.hit->rayToWorldPointDistanceSq;
if (thisDistSq < prevDistSq)
this->intersection = std::move(gltfIntersectResult.hit);
}
}
void TilesetHeightQuery::findCandidateTiles(
Tile* pTile,
std::vector<std::string>& warnings) {
// If tile failed to load, this means we can't complete the intersection
if (pTile->getState() == TileLoadState::Failed) {
warnings.emplace_back("Tile load failed during query. Ignoring.");
return;
}
const std::optional<BoundingVolume>& contentBoundingVolume =
pTile->getContentBoundingVolume();
if (pTile->getChildren().empty()) {
// This is a leaf node, it's a candidate
// If optional content bounding volume exists, test against it
if (contentBoundingVolume) {
if (boundingVolumeContainsCoordinate(
*contentBoundingVolume,
this->ray,
this->inputPosition,
this->ellipsoid)) {
this->candidateTiles.emplace_back(pTile);
}
} else {
this->candidateTiles.emplace_back(pTile);
}
} else {
// We have children
// If additive refinement, add parent to the list with children
if (pTile->getRefine() == TileRefine::Add) {
// If optional content bounding volume exists, test against it
if (contentBoundingVolume) {
if (boundingVolumeContainsCoordinate(
*contentBoundingVolume,
this->ray,
this->inputPosition,
this->ellipsoid)) {
this->additiveCandidateTiles.emplace_back(pTile);
}
} else {
this->additiveCandidateTiles.emplace_back(pTile);
}
}
// Traverse children
for (Tile& child : pTile->getChildren()) {
// if bounding volume doesn't intersect this ray, we can skip it
if (!boundingVolumeContainsCoordinate(
child.getBoundingVolume(),
this->ray,
this->inputPosition,
this->ellipsoid))
continue;
// Child is a candidate, traverse it and its children
findCandidateTiles(&child, warnings);
}
}
}
namespace {
bool tileHasRenderContent(const Tile& tile) {
return tile.getState() >= TileLoadState::ContentLoaded &&
tile.getContent().getRenderContent() != nullptr;
}
} // namespace
void TilesetHeightQuery::findLoadedCandidateTiles(
Tile* pTile,
std::vector<std::string>& warnings) {
if (pTile->getState() == TileLoadState::Failed) {
warnings.emplace_back("Tile load failed during query. Ignoring.");
return;
}
const std::optional<BoundingVolume>& contentBoundingVolume =
pTile->getContentBoundingVolume();
// Recurse into children whose bounding volumes intersect the ray,
// tracking whether any descendant became a candidate. We recurse even
// into children that are not yet loaded, because deeper descendants
// may be loaded.
bool anyDescendantCandidate = false;
if (!pTile->getChildren().empty()) {
for (Tile& child : pTile->getChildren()) {
if (!boundingVolumeContainsCoordinate(
child.getBoundingVolume(),
this->ray,
this->inputPosition,
this->ellipsoid))
continue;
size_t prevCount =
this->candidateTiles.size() + this->additiveCandidateTiles.size();
findLoadedCandidateTiles(&child, warnings);
if (this->candidateTiles.size() + this->additiveCandidateTiles.size() >
prevCount) {
anyDescendantCandidate = true;
}
}
}
bool isLeaf = pTile->getChildren().empty();
// For additive refinement, this tile is always a candidate alongside
// children.
if (!isLeaf && pTile->getRefine() == TileRefine::Add &&
tileHasRenderContent(*pTile)) {
if (contentBoundingVolume) {
if (boundingVolumeContainsCoordinate(
*contentBoundingVolume,
this->ray,
this->inputPosition,
this->ellipsoid)) {
this->additiveCandidateTiles.emplace_back(pTile);
}
} else {
this->additiveCandidateTiles.emplace_back(pTile);
}
}
// Use this tile as a leaf candidate if:
// - It is actually a leaf, OR
// - No descendant was found as a candidate AND this is not an
// additively-refined tile (those are already in additiveCandidateTiles)
// In either case, the tile must have renderable content.
if ((isLeaf ||
(!anyDescendantCandidate && pTile->getRefine() != TileRefine::Add)) &&
tileHasRenderContent(*pTile)) {
if (contentBoundingVolume) {
if (boundingVolumeContainsCoordinate(
*contentBoundingVolume,
this->ray,
this->inputPosition,
this->ellipsoid)) {
this->candidateTiles.emplace_back(pTile);
}
} else {
this->candidateTiles.emplace_back(pTile);
}
}
}
void TilesetHeightQuery::intersectCandidateTiles(
std::vector<std::string>& outWarnings) {
for (const Tile::Pointer& pTile : this->additiveCandidateTiles) {
this->intersectVisibleTile(pTile.get(), outWarnings);
}
for (const Tile::Pointer& pTile : this->candidateTiles) {
this->intersectVisibleTile(pTile.get(), outWarnings);
}
}
std::optional<double> TilesetHeightQuery::getHeightFromIntersection() const {
if (!this->intersection.has_value()) {
return std::nullopt;
}
return this->ellipsoid.getMaximumRadius() * rayOriginHeightFraction -
glm::sqrt(this->intersection->rayToWorldPointDistanceSq);
}
TilesetHeightRequest::TilesetHeightRequest(
std::vector<TilesetHeightQuery>&& queries_,
const CesiumAsync::Promise<SampleHeightResult>& promise_) noexcept
: queries(std::move(queries_)), promise(promise_) {}
TilesetHeightRequest::TilesetHeightRequest(
TilesetHeightRequest&& rhs) noexcept = default;
TilesetHeightRequest::~TilesetHeightRequest() noexcept = default;
/*static*/ void TilesetHeightRequest::processHeightRequests(
const AsyncSystem& asyncSystem,
TilesetContentManager& contentManager,
const TilesetOptions& options,
std::list<TilesetHeightRequest>& heightRequests) {
if (heightRequests.empty())
return;
// Go through all requests, either complete them, or gather the tiles they
// need for completion
for (auto it = heightRequests.begin(); it != heightRequests.end();) {
TilesetHeightRequest& request = *it;
if (!request
.tryCompleteHeightRequest(asyncSystem, contentManager, options)) {
++it;
} else {
auto deleteIt = it;
++it;
heightRequests.erase(deleteIt);
}
}
}
double TilesetHeightRequest::getWeight() const { return 1.0; }
bool TilesetHeightRequest::hasMoreTilesToLoadInWorkerThread() const {
return !this->tilesToLoad.empty();
}
const Tile* TilesetHeightRequest::getNextTileToLoadInWorkerThread() {
Tile* pResult = nullptr;
auto it = this->tilesToLoad.begin();
if (it != this->tilesToLoad.end()) {
pResult = *it;
this->tilesToLoad.erase(it);
}
return pResult;
}
bool TilesetHeightRequest::hasMoreTilesToLoadInMainThread() const {
// We don't need to do any main thread loading for height queries.
return false;
}
const Tile* TilesetHeightRequest::getNextTileToLoadInMainThread() {
return nullptr;
}
void Cesium3DTilesSelection::TilesetHeightRequest::failHeightRequests(
std::list<TilesetHeightRequest>& heightRequests,
const std::string& message) {
for (TilesetHeightRequest& request : heightRequests) {
SampleHeightResult result;
result.warnings.emplace_back(message);
result.sampleSuccess.resize(request.queries.size(), false);
result.positions.reserve(request.queries.size());
for (const TilesetHeightQuery& query : request.queries) {
result.positions.emplace_back(query.inputPosition);
}
request.promise.resolve(std::move(result));
}
heightRequests.clear();
}
bool TilesetHeightRequest::tryCompleteHeightRequest(
const AsyncSystem& asyncSystem,
TilesetContentManager& contentManager,
const TilesetOptions& options) {
this->tilesToLoad.clear();
// If this TilesetContentLoader supports direct height queries, use that
// instead of downloading tiles.
if (contentManager.getRootTile() &&
contentManager.getRootTile()->getLoader()) {
ITilesetHeightSampler* pSampler =
contentManager.getRootTile()->getLoader()->getHeightSampler();
if (pSampler) {
std::vector<Cartographic> positions;
positions.reserve(this->queries.size());
for (TilesetHeightQuery& query : this->queries) {
positions.emplace_back(query.inputPosition);
}
pSampler->sampleHeights(asyncSystem, std::move(positions))
.thenImmediately(
[promise = this->promise](SampleHeightResult&& result) {
promise.resolve(std::move(result));
});
return true;
}
}
// No direct height query possible, so download and sample tiles.
bool tileStillNeedsLoading = false;
std::vector<std::string> warnings;
for (TilesetHeightQuery& query : this->queries) {
if (query.candidateTiles.empty() && query.additiveCandidateTiles.empty()) {
// Find the initial set of tiles whose bounding volume is intersected by
// the query ray.
query.findCandidateTiles(contentManager.getRootTile(), warnings);
} else {
// Refine the current set of candidate tiles, in case further tiles from
// implicit tiling, external tilesets, etc. having been loaded since last
// frame.
std::swap(query.candidateTiles, query.previousCandidateTiles);
query.candidateTiles.clear();
for (const Tile::Pointer& pCandidate : query.previousCandidateTiles) {
TileLoadState loadState = pCandidate->getState();
if (!pCandidate->getChildren().empty() &&
loadState >= TileLoadState::ContentLoaded) {
query.findCandidateTiles(pCandidate.get(), warnings);
} else {
// Check again next frame to see if this tile has children.
query.candidateTiles.emplace_back(pCandidate);
}
}
}
auto checkTile =
[this, &contentManager, &options, &tileStillNeedsLoading](Tile* pTile) {
contentManager.createLatentChildrenIfNecessary(*pTile, options);
TileLoadState state = pTile->getState();
if (state == TileLoadState::Unloading) {
// This tile is in the process of unloading, which must complete
// before we can load it again.
contentManager.unloadTileContent(*pTile);
tileStillNeedsLoading = true;
} else if (state <= TileLoadState::ContentLoading) {
this->tilesToLoad.insert(pTile);
tileStillNeedsLoading = true;
}
};
// If any candidates need loading, add to return set
for (const Tile::Pointer& pTile : query.additiveCandidateTiles) {
checkTile(pTile.get());
}
for (const Tile::Pointer& pTile : query.candidateTiles) {
checkTile(pTile.get());
}
}
// Bail if we're waiting on tiles to load
if (tileStillNeedsLoading)
return false;
// Do the intersect tests
for (TilesetHeightQuery& query : this->queries) {
query.intersectCandidateTiles(warnings);
}
// All rays are done, create results
SampleHeightResult results;
// Start with any warnings from tile traversal
results.warnings = std::move(warnings);
results.positions.resize(this->queries.size(), Cartographic(0.0, 0.0, 0.0));
results.sampleSuccess.resize(this->queries.size());
// Populate results with completed queries
for (size_t i = 0; i < this->queries.size(); ++i) {
const TilesetHeightQuery& query = this->queries[i];
results.positions[i] = query.inputPosition;
std::optional<double> height = query.getHeightFromIntersection();
results.sampleSuccess[i] = height.has_value();
if (height.has_value()) {
results.positions[i].height = *height;
}
}
this->promise.resolve(std::move(results));
return true;
}