-
Notifications
You must be signed in to change notification settings - Fork 270
Expand file tree
/
Copy pathRasterOverlayUtilities.cpp
More file actions
2067 lines (1816 loc) · 70.3 KB
/
Copy pathRasterOverlayUtilities.cpp
File metadata and controls
2067 lines (1816 loc) · 70.3 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
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
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <CesiumGeometry/QuadtreeTileID.h>
#include <CesiumGeometry/Rectangle.h>
#include <CesiumGeometry/clipTriangleAtAxisAlignedThreshold.h>
#include <CesiumGeospatial/BoundingRegionBuilder.h>
#include <CesiumGeospatial/Cartographic.h>
#include <CesiumGeospatial/Ellipsoid.h>
#include <CesiumGeospatial/GlobeRectangle.h>
#include <CesiumGeospatial/Projection.h>
#include <CesiumGltf/Accessor.h>
#include <CesiumGltf/AccessorView.h>
#include <CesiumGltf/AccessorWriter.h>
#include <CesiumGltf/BufferView.h>
#include <CesiumGltf/ExtensionModelExtStructuralMetadata.h>
#include <CesiumGltf/Image.h>
#include <CesiumGltf/Mesh.h>
#include <CesiumGltf/MeshPrimitive.h>
#include <CesiumGltf/Model.h>
#include <CesiumGltf/PropertyTableProperty.h>
#include <CesiumGltfContent/GltfUtilities.h>
#include <CesiumGltfContent/SkirtMeshMetadata.h>
#include <CesiumRasterOverlays/RasterOverlayDetails.h>
#include <CesiumRasterOverlays/RasterOverlayUtilities.h>
#include <CesiumUtility/Assert.h>
#include <CesiumUtility/Math.h>
#include <CesiumUtility/Tracing.h>
#include <glm/common.hpp>
#include <glm/detail/setup.hpp>
#include <glm/ext/matrix_double4x4.hpp>
#include <glm/ext/vector_double3.hpp>
#include <glm/ext/vector_float2.hpp>
#include <glm/ext/vector_float3.hpp>
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <limits>
#include <optional>
#include <stdexcept>
#include <string>
#include <string_view>
#include <utility>
#include <variant>
#include <vector>
using namespace CesiumGltf;
using namespace CesiumGltfContent;
using namespace CesiumGeometry;
using namespace CesiumGeospatial;
namespace CesiumRasterOverlays {
/*static*/ std::optional<RasterOverlayDetails>
RasterOverlayUtilities::createRasterOverlayTextureCoordinates(
CesiumGltf::Model& model,
const glm::dmat4& modelToEcefTransform,
const std::optional<CesiumGeospatial::GlobeRectangle>& globeRectangle,
std::vector<CesiumGeospatial::Projection>&& projections,
bool invertVCoordinate,
const std::string_view& textureCoordinateAttributeBaseName,
int32_t firstTextureCoordinateID) {
if (projections.empty()) {
return std::nullopt;
}
const Ellipsoid& ellipsoid = getProjectionEllipsoid(projections.front());
// Compute the bounds of the tile if they're not provided.
CesiumGeospatial::GlobeRectangle bounds =
globeRectangle ? *globeRectangle
: GltfUtilities::computeBoundingRegion(
model,
modelToEcefTransform,
ellipsoid)
.getRectangle();
// Don't let the bounding rectangle cross the anti-meridian. If it does, split
// it into two rectangles. Ideally we'd map both of them (separately) to the
// model, but in our current "only Geographic and Web Mercator are supported"
// world, crossing the anti-meridian is almost certain to simply be numerical
// noise. So we just use the larger of the two rectangles.
std::pair<GlobeRectangle, std::optional<GlobeRectangle>> splits =
bounds.splitAtAntiMeridian();
bounds = splits.first;
// Currently, a Longitude/Latitude Rectangle maps perfectly to all possible
// projection types, because the only possible projection types are
// Geographic and Web Mercator. In the future if/when we add projections
// that don't have this convenient property, we'll need to compute the
// Rectangle for each projection directly from the vertex positions.
std::vector<CesiumGeometry::Rectangle> rectangles(projections.size());
for (size_t i = 0; i < projections.size(); ++i) {
rectangles[i] = projectRectangleSimple(projections[i], bounds);
}
glm::dmat4 rootTransform = modelToEcefTransform;
rootTransform = GltfUtilities::applyRtcCenter(model, rootTransform);
rootTransform = GltfUtilities::applyGltfUpAxisTransform(model, rootTransform);
std::vector<int> positionAccessorsToTextureCoordinateAccessor;
positionAccessorsToTextureCoordinateAccessor.resize(
model.accessors.size(),
0);
// When computing the tile's bounds, ignore vertices that are less than
// 1/1000th of a tile height from the North or South pole. Longitudes cannot
// be trusted at such extreme latitudes.
CesiumGeospatial::BoundingRegionBuilder computedBounds;
computedBounds.setPoleTolerance(0.001 * bounds.computeHeight());
auto createTextureCoordinatesForPrimitive =
[&](CesiumGltf::Model& gltf,
CesiumGltf::Node& /*node*/,
CesiumGltf::Mesh& /*mesh*/,
CesiumGltf::MeshPrimitive& primitive,
const glm::dmat4& nodeTransform) {
auto positionIt = primitive.attributes.find("POSITION");
if (positionIt == primitive.attributes.end()) {
return;
}
const int positionAccessorIndex = positionIt->second;
if (positionAccessorIndex < 0 ||
positionAccessorIndex >= static_cast<int>(gltf.accessors.size())) {
return;
}
const int32_t firstTextureCoordinateAccessorIndex =
positionAccessorsToTextureCoordinateAccessor[static_cast<size_t>(
positionAccessorIndex)];
if (firstTextureCoordinateAccessorIndex > 0) {
// Already created texture coordinates for this projection, so use
// them.
for (size_t i = 0; i < projections.size(); ++i) {
std::string attributeName =
std::string(textureCoordinateAttributeBaseName) +
std::to_string(firstTextureCoordinateID + int32_t(i));
primitive.attributes[attributeName] =
firstTextureCoordinateAccessorIndex + int32_t(i);
}
return;
}
const glm::dmat4 fullTransform = rootTransform * nodeTransform;
std::vector<CesiumGltf::Buffer>& buffers = gltf.buffers;
std::vector<CesiumGltf::BufferView>& bufferViews = gltf.bufferViews;
std::vector<CesiumGltf::Accessor>& accessors = gltf.accessors;
positionAccessorsToTextureCoordinateAccessor[size_t(
positionAccessorIndex)] = int32_t(gltf.accessors.size());
// Create a buffer, bufferView, accessor, and writer for each set of
// coordinates. Reserve space for them to avoid unnecessary
// reallocations and to prevent earlier buffers from becoming invalid
// after we've created an AccessorWriter for it and then add _another_
// buffer.
std::vector<CesiumGltf::AccessorWriter<glm::vec2>> uvWriters;
std::vector<std::vector<double>*> mins;
std::vector<std::vector<double>*> maxs;
uvWriters.reserve(projections.size());
mins.reserve(projections.size());
maxs.reserve(projections.size());
buffers.reserve(buffers.size() + projections.size());
bufferViews.reserve(bufferViews.size() + projections.size());
accessors.reserve(accessors.size() + projections.size());
const CesiumGltf::AccessorView<glm::vec3> positionView(
gltf,
positionAccessorIndex);
if (positionView.status() != CesiumGltf::AccessorViewStatus::Valid) {
return;
}
std::optional<SkirtMeshMetadata> skirtMeshMetadata =
SkirtMeshMetadata::parseFromGltfExtras(primitive.extras);
int64_t vertexBegin, vertexEnd;
if (skirtMeshMetadata.has_value()) {
vertexBegin = skirtMeshMetadata->noSkirtVerticesBegin;
vertexEnd = skirtMeshMetadata->noSkirtVerticesBegin +
skirtMeshMetadata->noSkirtVerticesCount;
} else {
vertexBegin = 0;
vertexEnd = positionView.size();
}
for (size_t i = 0; i < projections.size(); ++i) {
const int uvBufferId = static_cast<int>(buffers.size());
CesiumGltf::Buffer& uvBuffer = buffers.emplace_back();
const int uvBufferViewId = static_cast<int>(bufferViews.size());
bufferViews.emplace_back();
const int uvAccessorId = static_cast<int>(accessors.size());
accessors.emplace_back();
uvBuffer.cesium.data.resize(
size_t(positionView.size()) * 2 * sizeof(float));
uvBuffer.byteLength = int64_t(uvBuffer.cesium.data.size());
CesiumGltf::BufferView& uvBufferView =
gltf.bufferViews[static_cast<size_t>(uvBufferViewId)];
uvBufferView.buffer = uvBufferId;
uvBufferView.byteOffset = 0;
uvBufferView.byteStride = 2 * sizeof(float);
uvBufferView.byteLength = int64_t(uvBuffer.cesium.data.size());
uvBufferView.target = CesiumGltf::BufferView::Target::ARRAY_BUFFER;
CesiumGltf::Accessor& uvAccessor =
gltf.accessors[static_cast<size_t>(uvAccessorId)];
uvAccessor.bufferView = uvBufferViewId;
uvAccessor.byteOffset = 0;
uvAccessor.componentType = CesiumGltf::Accessor::ComponentType::FLOAT;
uvAccessor.count = int64_t(positionView.size());
uvAccessor.type = CesiumGltf::Accessor::Type::VEC2;
uvAccessor.min = {1.0, 1.0};
uvAccessor.max = {0.0, 0.0};
[[maybe_unused]] CesiumGltf::AccessorWriter<glm::vec2>& uvWriter =
uvWriters.emplace_back(gltf, uvAccessorId);
CESIUM_ASSERT(
uvWriter.status() == CesiumGltf::AccessorViewStatus::Valid);
std::string attributeName =
std::string(textureCoordinateAttributeBaseName) +
std::to_string(firstTextureCoordinateID + int32_t(i));
primitive.attributes[attributeName] = uvAccessorId;
mins.emplace_back(&uvAccessor.min);
maxs.emplace_back(&uvAccessor.max);
}
// Generate texture coordinates for each position.
for (int64_t positionIndex = 0; positionIndex < positionView.size();
++positionIndex) {
// Get the ECEF position
const glm::vec3 position = positionView[positionIndex];
const glm::dvec3 positionEcef =
glm::dvec3(fullTransform * glm::dvec4(position, 1.0));
// Convert it to cartographic
const std::optional<CesiumGeospatial::Cartographic> cartographic =
ellipsoid.cartesianToCartographic(positionEcef);
if (!cartographic) {
for (CesiumGltf::AccessorWriter<glm::vec2>& uvWriter : uvWriters) {
uvWriter[positionIndex] = glm::dvec2(0.0, 0.0);
}
continue;
}
// exclude skirt vertices from bounds
if (positionIndex >= vertexBegin && positionIndex < vertexEnd) {
computedBounds.expandToIncludePosition(*cartographic);
}
// Generate texture coordinates at this position for each projection
for (size_t projectionIndex = 0; projectionIndex < projections.size();
++projectionIndex) {
const CesiumGeospatial::Projection& projection =
projections[projectionIndex];
const CesiumGeometry::Rectangle& rectangle =
rectangles[projectionIndex];
// Project it with the raster overlay's projection
glm::dvec3 projectedPosition =
projectPosition(projection, cartographic.value());
double longitude = cartographic.value().longitude;
const double latitude = cartographic.value().latitude;
const double ellipsoidHeight = cartographic.value().height;
// If the position is near the anti-meridian and the projected
// position is outside the expected range, try using the equivalent
// longitude on the other side of the anti-meridian to see if that
// gets us closer.
if (glm::abs(
glm::abs(cartographic.value().longitude) -
CesiumUtility::Math::OnePi) <
CesiumUtility::Math::Epsilon5 &&
(projectedPosition.x < rectangle.minimumX ||
projectedPosition.x > rectangle.maximumX ||
projectedPosition.y < rectangle.minimumY ||
projectedPosition.y > rectangle.maximumY)) {
const double testLongitude = longitude + longitude < 0.0
? CesiumUtility::Math::TwoPi
: -CesiumUtility::Math::TwoPi;
const glm::dvec3 projectedPosition2 = projectPosition(
projection,
CesiumGeospatial::Cartographic(
testLongitude,
latitude,
ellipsoidHeight));
const double distance1 = rectangle.computeSignedDistance(
glm::dvec2(projectedPosition));
const double distance2 = rectangle.computeSignedDistance(
glm::dvec2(projectedPosition2));
if (distance2 < distance1) {
projectedPosition = projectedPosition2;
longitude = testLongitude;
}
}
// Scale to (0.0, 0.0) at the (minimumX, minimumY) corner, and
// (1.0, 1.0) at the (maximumX, maximumY) corner. The coordinates
// should stay inside these bounds if the input rectangle actually
// bounds the vertices, but we'll clamp to be safe.
glm::vec2 uv(
CesiumUtility::Math::clamp(
(projectedPosition.x - rectangle.minimumX) /
rectangle.computeWidth(),
0.0,
1.0),
CesiumUtility::Math::clamp(
(projectedPosition.y - rectangle.minimumY) /
rectangle.computeHeight(),
0.0,
1.0));
if (invertVCoordinate) {
uv.y = 1.0f - uv.y;
}
mins[projectionIndex]->at(0) =
glm::min(mins[projectionIndex]->at(0), double(uv.x));
mins[projectionIndex]->at(1) =
glm::min(mins[projectionIndex]->at(1), double(uv.y));
maxs[projectionIndex]->at(0) =
glm::max(maxs[projectionIndex]->at(0), double(uv.x));
maxs[projectionIndex]->at(1) =
glm::max(maxs[projectionIndex]->at(1), double(uv.y));
uvWriters[projectionIndex][positionIndex] = uv;
}
}
};
model.forEachPrimitiveInScene(-1, createTextureCoordinatesForPrimitive);
return RasterOverlayDetails{
std::move(projections),
std::move(rectangles),
computedBounds.toRegion(ellipsoid)};
}
namespace {
struct EdgeVertex {
uint32_t index;
glm::vec2 uv;
};
struct EdgeIndices {
std::vector<EdgeVertex> west;
std::vector<EdgeVertex> south;
std::vector<EdgeVertex> east;
std::vector<EdgeVertex> north;
};
bool upsamplePrimitiveForRasterOverlays(
const Model& parentModel,
Model& model,
Mesh& mesh,
MeshPrimitive& primitive,
CesiumGeometry::UpsampledQuadtreeNode childID,
bool hasInvertedVCoordinate,
const std::string_view& textureCoordinateAttributeBaseName,
int32_t textureCoordinateIndex,
const CesiumGeospatial::Ellipsoid& ellipsoid);
struct FloatVertexAttribute {
const std::vector<std::byte>& buffer;
int64_t offset;
int64_t stride;
int64_t numberOfFloatsPerVertex;
int32_t accessorIndex;
std::vector<double> minimums;
std::vector<double> maximums;
};
void addClippedPolygon(
std::vector<float>& output,
std::vector<uint32_t>& indices,
std::vector<FloatVertexAttribute>& attributes,
std::vector<uint32_t>& vertexMap,
std::vector<uint32_t>& clipVertexToIndices,
const std::vector<CesiumGeometry::TriangleClipVertex>& complements,
const std::vector<CesiumGeometry::TriangleClipVertex>& clipResult);
void addEdge(
EdgeIndices& edgeIndices,
double thresholdU,
double thresholdV,
bool keepAboveU,
bool keepAboveV,
bool invertV,
const AccessorView<glm::vec2>& uvs,
const std::vector<uint32_t>& clipVertexToIndices,
const std::vector<CesiumGeometry::TriangleClipVertex>& complements,
const std::vector<CesiumGeometry::TriangleClipVertex>& clipResult);
void addSkirt(
std::vector<float>& output,
std::vector<uint32_t>& indices,
std::vector<FloatVertexAttribute>& attributes,
const std::vector<uint32_t>& edgeIndices,
const glm::dvec3& center,
double skirtHeight,
int64_t vertexSizeFloats,
int32_t positionAttributeIndex,
const CesiumGeospatial::Ellipsoid& ellipsoid);
void addSkirts(
std::vector<float>& output,
std::vector<uint32_t>& indices,
std::vector<FloatVertexAttribute>& attributes,
CesiumGeometry::UpsampledQuadtreeNode childID,
SkirtMeshMetadata& currentSkirt,
const SkirtMeshMetadata& parentSkirt,
EdgeIndices& edgeIndices,
int64_t vertexSizeFloats,
int32_t positionAttributeIndex,
bool hasInvertedVCoordinate,
const CesiumGeospatial::Ellipsoid& ellipsoid);
bool isWestChild(CesiumGeometry::UpsampledQuadtreeNode childID) noexcept {
return (childID.tileID.x % 2) == 0;
}
bool isSouthChild(CesiumGeometry::UpsampledQuadtreeNode childID) noexcept {
return (childID.tileID.y % 2) == 0;
}
void copyImages(const Model& parentModel, Model& result);
void copyMetadataTables(const Model& parentModel, Model& result);
/**
* @brief Helper struct for working with non-indexed triangles. Returns either
* the indices from an index accessor view, or generates new indices.
*/
template <typename TIndex> struct IndicesViewRemapper {
IndicesViewRemapper(
const Model& model,
const MeshPrimitive& primitive,
int32_t primitiveIndices,
int64_t numVertices)
: accessorView(std::nullopt),
indicesCount(0),
primitiveMode(primitive.mode) {
AccessorView<TIndex> view(model, primitiveIndices);
viewStatus = view.status();
if (viewStatus == AccessorViewStatus::Valid) {
accessorView = std::move(view);
if (primitiveMode == MeshPrimitive::Mode::TRIANGLES) {
indicesCount = accessorView->size();
} else if (
primitiveMode == MeshPrimitive::Mode::TRIANGLE_STRIP ||
primitiveMode == MeshPrimitive::Mode::TRIANGLE_FAN) {
// With a triangle strip or fan, each additional vertex past the first
// three adds an additional triangle
indicesCount = (accessorView->size() - 2) * 3;
}
} else if (primitiveIndices < 0) {
// Non-indexed triangles
indicesCount = numVertices;
viewStatus = AccessorViewStatus::Valid;
}
}
int64_t size() const { return indicesCount; }
AccessorViewStatus status() const { return viewStatus; }
const TIndex operator[](int64_t i) const {
if (i < 0 || i >= indicesCount) {
throw std::range_error("index out of range");
}
if (accessorView && primitiveMode == MeshPrimitive::Mode::TRIANGLES) {
return (*accessorView)[i];
} else if (
accessorView && primitiveMode == MeshPrimitive::Mode::TRIANGLE_STRIP) {
// Indices 0, 1, 2 map normally, indices 3, 4, 5 map to 2, 1, 3,
// indices 6, 7, 8 map to 2, 3, 4, etc.
const int64_t startIndex = i / 3;
const int64_t triIndex = i % 3;
// For every other triangle we need to reverse the order of the first two
// indices to maintain proper winding.
if (startIndex % 2 == 1 && triIndex < 2) {
return triIndex == 0 ? (*accessorView)[startIndex + 1]
: (*accessorView)[startIndex];
}
return (*accessorView)[startIndex + triIndex];
} else if (
accessorView && primitiveMode == MeshPrimitive::Mode::TRIANGLE_FAN) {
// Indices 0, 1, 2 map normally, indices 3, 4, 5 map to 0, 2, 3,
// indices 6, 7, 8 map to 0, 3, 4, etc.
const int64_t startIndex = i / 3;
const int64_t triIndex = i % 3;
if (triIndex == 0) {
return (*accessorView)[0];
}
return (*accessorView)[startIndex + triIndex];
}
// The indices of a non-indexed primitive are simply 0, 1, 2, 3, 4...
return static_cast<TIndex>(i);
}
private:
std::optional<AccessorView<TIndex>> accessorView;
int64_t indicesCount;
int32_t primitiveMode;
AccessorViewStatus viewStatus;
};
} // namespace
/*static*/ std::optional<Model>
RasterOverlayUtilities::upsampleGltfForRasterOverlays(
const Model& parentModel,
UpsampledQuadtreeNode childID,
bool hasInvertedVCoordinate,
const std::string_view& textureCoordinateAttributeBaseName,
int32_t textureCoordinateIndex,
const CesiumGeospatial::Ellipsoid& ellipsoid) {
CESIUM_TRACE("upsampleGltfForRasterOverlays");
Model result;
// Copy the entire parent model except for the buffers, bufferViews, and
// accessors, which we'll be rewriting.
result.animations = parentModel.animations;
result.materials = parentModel.materials;
result.meshes = parentModel.meshes;
result.nodes = parentModel.nodes;
result.textures = parentModel.textures;
result.images = parentModel.images;
result.skins = parentModel.skins;
result.samplers = parentModel.samplers;
result.cameras = parentModel.cameras;
result.scenes = parentModel.scenes;
result.scene = parentModel.scene;
result.extensionsUsed = parentModel.extensionsUsed;
result.extensionsRequired = parentModel.extensionsRequired;
result.asset = parentModel.asset;
result.extras = parentModel.extras;
// TODO: check if this is enough, not enough, or overkill
result.extensions = parentModel.extensions;
// result.extras_json_string = parentModel.extras_json_string;
// result.extensions_json_string = parentModel.extensions_json_string;
copyImages(parentModel, result);
// Copy EXT_structural_metadata property table buffer views and unique
// buffers.
copyMetadataTables(parentModel, result);
// If the glTF has a name, update it with upsample info.
auto nameIt = result.extras.find("Cesium3DTiles_TileUrl");
if (nameIt != result.extras.end()) {
std::string name = nameIt->second.getStringOrDefault("");
const std::string::size_type upsampledIndex = name.find(" upsampled");
if (upsampledIndex != std::string::npos) {
name = name.substr(0, upsampledIndex);
}
name += " upsampled L" + std::to_string(childID.tileID.level);
name += "-X" + std::to_string(childID.tileID.x);
name += "-Y" + std::to_string(childID.tileID.y);
nameIt->second = name;
}
bool containsPrimitives = false;
for (Mesh& mesh : result.meshes) {
for (size_t i = 0; i < mesh.primitives.size(); ++i) {
MeshPrimitive& primitive = mesh.primitives[i];
bool keep = upsamplePrimitiveForRasterOverlays(
parentModel,
result,
mesh,
primitive,
childID,
hasInvertedVCoordinate,
textureCoordinateAttributeBaseName,
textureCoordinateIndex,
ellipsoid);
// We're assuming here that nothing references primitives by index, so we
// can remove them without any drama.
if (!keep) {
mesh.primitives.erase(mesh.primitives.begin() + ptrdiff_t(i));
--i;
}
}
containsPrimitives |= !mesh.primitives.empty();
}
return containsPrimitives ? std::make_optional<Model>(std::move(result))
: std::nullopt;
}
/*static*/ glm::dvec2 RasterOverlayUtilities::computeDesiredScreenPixels(
double geometricError,
double maximumScreenSpaceError,
const CesiumGeospatial::Projection& projection,
const CesiumGeometry::Rectangle& rectangle,
const CesiumGeospatial::Ellipsoid& ellipsoid) {
// We're aiming to estimate the maximum number of pixels (in each projected
// direction) the tile will occupy on the screen. They will be determined by
// the tile's geometric error, because when less error is needed (i.e. the
// viewer moved closer), the LOD will switch to show the tile's children
// instead of this tile.
//
// It works like this:
// * Estimate the size of the projected rectangle in world coordinates.
// * Compute the distance at which tile will switch to its children, based on
// its geometric error and the tileset SSE.
// * Compute the on-screen size of the projected rectangle at that distance.
//
// For the two compute steps, we use the usual perspective projection SSE
// equation:
// screenSize = (realSize * viewportHeight) / (distance * 2 * tan(0.5 * fovY))
//
// Conveniently a bunch of terms cancel out, so the screen pixel size at the
// switch distance is not actually dependent on the screen dimensions or
// field-of-view angle.
// We can get a more accurate estimate of the real-world size of the projected
// rectangle if we consider the rectangle at the true height of the geometry
// rather than assuming it's on the ellipsoid. This will make basically no
// difference for small tiles (because surface normals on opposite ends of
// tiles are effectively identical), and only a small difference for large
// ones (because heights will be small compared to the total size of a large
// tile). So we're skipping this complexity for now and estimating geometry
// width/height as if it's on the ellipsoid surface.
const double heightForSizeEstimation = 0.0;
glm::dvec2 diameters = computeProjectedRectangleSize(
projection,
rectangle,
heightForSizeEstimation,
ellipsoid);
return diameters * maximumScreenSpaceError / geometricError;
}
/*static*/ glm::dvec4 RasterOverlayUtilities::computeTranslationAndScale(
const Rectangle& geometryRectangle,
const Rectangle& overlayRectangle) {
const double geometryWidth = geometryRectangle.computeWidth();
const double geometryHeight = geometryRectangle.computeHeight();
const double scaleX = geometryWidth / overlayRectangle.computeWidth();
const double scaleY = geometryHeight / overlayRectangle.computeHeight();
glm::dvec2 translation = glm::dvec2(
(scaleX * (geometryRectangle.minimumX - overlayRectangle.minimumX)) /
geometryWidth,
(scaleY * (geometryRectangle.minimumY - overlayRectangle.minimumY)) /
geometryHeight);
glm::dvec2 scale = glm::dvec2(scaleX, scaleY);
return glm::dvec4(translation, scale);
}
namespace {
void copyVertexAttributes(
std::vector<FloatVertexAttribute>& vertexAttributes,
const CesiumGeometry::TriangleClipVertex& vertex,
std::vector<float>& output,
bool skipMinMaxUpdate = false) {
struct Operation {
std::vector<FloatVertexAttribute>& vertexAttributes;
std::vector<float>& output;
bool skipMinMaxUpdate;
void operator()(int vertexIndex) {
for (FloatVertexAttribute& attribute : vertexAttributes) {
const float* pInput = reinterpret_cast<const float*>(
attribute.buffer.data() + attribute.offset +
attribute.stride * vertexIndex);
for (int32_t i = 0; i < attribute.numberOfFloatsPerVertex; ++i) {
const float value = *pInput;
output.push_back(value);
if (!skipMinMaxUpdate) {
attribute.minimums[static_cast<size_t>(i)] = glm::min(
attribute.minimums[static_cast<size_t>(i)],
static_cast<double>(value));
attribute.maximums[static_cast<size_t>(i)] = glm::max(
attribute.maximums[static_cast<size_t>(i)],
static_cast<double>(value));
}
++pInput;
}
}
}
void operator()(const CesiumGeometry::InterpolatedVertex& vertex) {
for (FloatVertexAttribute& attribute : vertexAttributes) {
const float* pInput0 = reinterpret_cast<const float*>(
attribute.buffer.data() + attribute.offset +
attribute.stride * vertex.first);
const float* pInput1 = reinterpret_cast<const float*>(
attribute.buffer.data() + attribute.offset +
attribute.stride * vertex.second);
for (int32_t i = 0; i < attribute.numberOfFloatsPerVertex; ++i) {
const float value = glm::mix(*pInput0, *pInput1, vertex.t);
output.push_back(value);
if (!skipMinMaxUpdate) {
attribute.minimums[static_cast<size_t>(i)] = glm::min(
attribute.minimums[static_cast<size_t>(i)],
static_cast<double>(value));
attribute.maximums[static_cast<size_t>(i)] = glm::max(
attribute.maximums[static_cast<size_t>(i)],
static_cast<double>(value));
}
++pInput0;
++pInput1;
}
}
}
};
std::visit(Operation{vertexAttributes, output, skipMinMaxUpdate}, vertex);
}
void copyVertexAttributes(
std::vector<FloatVertexAttribute>& vertexAttributes,
const std::vector<CesiumGeometry::TriangleClipVertex>& complements,
const CesiumGeometry::TriangleClipVertex& vertex,
std::vector<float>& output) {
struct Operation {
std::vector<FloatVertexAttribute>& vertexAttributes;
const std::vector<CesiumGeometry::TriangleClipVertex>& complements;
std::vector<float>& output;
void operator()(int vertexIndex) {
if (vertexIndex < 0) {
copyVertexAttributes(
vertexAttributes,
complements[static_cast<size_t>(~vertexIndex)],
output);
} else {
copyVertexAttributes(vertexAttributes, vertexIndex, output);
}
}
void operator()(const CesiumGeometry::InterpolatedVertex& vertex) {
size_t outputIndex0 = output.size();
// Copy the two vertices into the output array
if (vertex.first < 0) {
copyVertexAttributes(
vertexAttributes,
complements[static_cast<size_t>(~vertex.first)],
output,
true);
} else {
copyVertexAttributes(vertexAttributes, vertex.first, output, true);
}
size_t outputIndex1 = output.size();
if (vertex.second < 0) {
copyVertexAttributes(
vertexAttributes,
complements[static_cast<size_t>(~vertex.second)],
output,
true);
} else {
copyVertexAttributes(vertexAttributes, vertex.second, output, true);
}
// Interpolate between them and overwrite the first with the result.
for (FloatVertexAttribute& attribute : vertexAttributes) {
for (int32_t i = 0; i < attribute.numberOfFloatsPerVertex; ++i) {
float value =
glm::mix(output[outputIndex0], output[outputIndex1], vertex.t);
output[outputIndex0] = value;
attribute.minimums[static_cast<size_t>(i)] = glm::min(
attribute.minimums[static_cast<size_t>(i)],
static_cast<double>(value));
attribute.maximums[static_cast<size_t>(i)] = glm::max(
attribute.maximums[static_cast<size_t>(i)],
static_cast<double>(value));
++outputIndex0;
++outputIndex1;
}
}
// Remove the temporary second, which is now pointed to be outputIndex0.
output.erase(
output.begin() +
static_cast<std::vector<float>::iterator::difference_type>(
outputIndex0),
output.end());
}
};
std::visit(
Operation{
vertexAttributes,
complements,
output,
},
vertex);
}
template <class T>
T getVertexValue(
const AccessorView<T>& accessor,
const CesiumGeometry::TriangleClipVertex& vertex) {
struct Operation {
const AccessorView<T>& accessor;
T operator()(int vertexIndex) { return accessor[vertexIndex]; }
T operator()(const CesiumGeometry::InterpolatedVertex& vertex) {
const T& v0 = accessor[vertex.first];
const T& v1 = accessor[vertex.second];
return glm::mix(v0, v1, vertex.t);
}
};
return std::visit(Operation{accessor}, vertex);
}
template <class T>
T getVertexValue(
const AccessorView<T>& accessor,
const std::vector<CesiumGeometry::TriangleClipVertex>& complements,
const CesiumGeometry::TriangleClipVertex& vertex) {
struct Operation {
const AccessorView<T>& accessor;
const std::vector<CesiumGeometry::TriangleClipVertex>& complements;
T operator()(int vertexIndex) {
if (vertexIndex < 0) {
return getVertexValue(
accessor,
complements,
complements[static_cast<size_t>(~vertexIndex)]);
}
return accessor[vertexIndex];
}
T operator()(const CesiumGeometry::InterpolatedVertex& vertex) {
T v0{};
if (vertex.first < 0) {
v0 = getVertexValue(
accessor,
complements,
complements[static_cast<size_t>(~vertex.first)]);
} else {
v0 = accessor[vertex.first];
}
T v1{};
if (vertex.second < 0) {
v1 = getVertexValue(
accessor,
complements,
complements[static_cast<size_t>(~vertex.second)]);
} else {
v1 = accessor[vertex.second];
}
return glm::mix(v0, v1, vertex.t);
}
};
return std::visit(Operation{accessor, complements}, vertex);
}
void scaleWaterMask(
MeshPrimitive& primitive,
CesiumGeometry::UpsampledQuadtreeNode childID) {
bool onlyWater = false;
bool onlyLand = true;
int64_t waterMaskTextureId = -1;
auto onlyWaterIt = primitive.extras.find("OnlyWater");
auto onlyLandIt = primitive.extras.find("OnlyLand");
if (onlyWaterIt != primitive.extras.end() && onlyWaterIt->second.isBool() &&
onlyLandIt != primitive.extras.end() && onlyLandIt->second.isBool()) {
onlyWater = onlyWaterIt->second.getBoolOrDefault(false);
onlyLand = onlyLandIt->second.getBoolOrDefault(true);
if (!onlyWater && !onlyLand) {
// We have to use the parent's water mask
auto waterMaskTextureIdIt = primitive.extras.find("WaterMaskTex");
if (waterMaskTextureIdIt != primitive.extras.end() &&
waterMaskTextureIdIt->second.isInt64()) {
waterMaskTextureId = waterMaskTextureIdIt->second.getInt64OrDefault(-1);
}
}
}
double waterMaskTranslationX = 0.0;
double waterMaskTranslationY = 0.0;
double waterMaskScale = 0.0;
auto waterMaskTranslationXIt = primitive.extras.find("WaterMaskTranslationX");
auto waterMaskTranslationYIt = primitive.extras.find("WaterMaskTranslationY");
auto waterMaskScaleIt = primitive.extras.find("WaterMaskScale");
if (waterMaskTranslationXIt != primitive.extras.end() &&
waterMaskTranslationXIt->second.isDouble() &&
waterMaskTranslationYIt != primitive.extras.end() &&
waterMaskTranslationYIt->second.isDouble() &&
waterMaskScaleIt != primitive.extras.end() &&
waterMaskScaleIt->second.isDouble()) {
waterMaskScale = 0.5 * waterMaskScaleIt->second.getDoubleOrDefault(0.0);
waterMaskTranslationX =
waterMaskTranslationXIt->second.getDoubleOrDefault(0.0) +
waterMaskScale * (childID.tileID.x % 2);
waterMaskTranslationY =
waterMaskTranslationYIt->second.getDoubleOrDefault(0.0) +
waterMaskScale * (childID.tileID.y % 2);
}
primitive.extras.insert_or_assign("OnlyWater", onlyWater);
primitive.extras.insert_or_assign("OnlyLand", onlyLand);
primitive.extras.insert_or_assign("WaterMaskTex", waterMaskTextureId);
primitive.extras.insert_or_assign(
"WaterMaskTranslationX",
waterMaskTranslationX);
primitive.extras.insert_or_assign(
"WaterMaskTranslationY",
waterMaskTranslationY);
primitive.extras.insert_or_assign("WaterMaskScale", waterMaskScale);
}
bool upsamplePointsPrimitiveForRasterOverlays(
const Model& parentModel,
Model& model,
MeshPrimitive& primitive,
CesiumGeometry::UpsampledQuadtreeNode childID,
bool hasInvertedVCoordinate,
const std::string_view& textureCoordinateAttributeBaseName,
int32_t textureCoordinateIndex) {
CESIUM_TRACE("upsamplePointsPrimitiveForRasterOverlays");
// Add up the per-vertex size of all attributes and create buffers,
// bufferViews, and accessors
std::vector<FloatVertexAttribute> attributes;
attributes.reserve(primitive.attributes.size());
const size_t vertexBufferIndex = model.buffers.size();
model.buffers.emplace_back();
const size_t vertexBufferViewIndex = model.bufferViews.size();
model.bufferViews.emplace_back();
BufferView& vertexBufferView = model.bufferViews[vertexBufferViewIndex];
vertexBufferView.buffer = static_cast<int>(vertexBufferIndex);
vertexBufferView.target = BufferView::Target::ARRAY_BUFFER;
int64_t vertexSizeFloats = 0;
int32_t uvAccessorIndex = -1;
std::vector<std::string> toRemove;
std::string textureCoordinateName =
std::string(textureCoordinateAttributeBaseName) +
std::to_string(textureCoordinateIndex);
for (std::pair<const std::string, int>& attribute : primitive.attributes) {
if (attribute.first.starts_with(textureCoordinateAttributeBaseName)) {
if (uvAccessorIndex == -1) {
if (attribute.first == textureCoordinateName) {
uvAccessorIndex = attribute.second;
}
}
// Do not include textureCoordinateName (e.g., TEXCOORD_* or
// _CESIUMOVERLAY_*), it will be generated later.
toRemove.push_back(attribute.first);
continue;
}
if (attribute.second < 0 ||
attribute.second >= static_cast<int>(parentModel.accessors.size())) {
toRemove.push_back(attribute.first);
continue;
}
const Accessor& accessor =
parentModel.accessors[static_cast<size_t>(attribute.second)];
if (accessor.bufferView < 0 ||
accessor.bufferView >=
static_cast<int>(parentModel.bufferViews.size())) {
toRemove.push_back(attribute.first);
continue;