GoogleEarthEnterpriseTerrainData.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  1. import BoundingSphere from "./BoundingSphere.js";
  2. import Cartesian2 from "./Cartesian2.js";
  3. import Cartesian3 from "./Cartesian3.js";
  4. import Check from "./Check.js";
  5. import defaultValue from "./defaultValue.js";
  6. import defined from "./defined.js";
  7. import DeveloperError from "./DeveloperError.js";
  8. import IndexDatatype from "./IndexDatatype.js";
  9. import Intersections2D from "./Intersections2D.js";
  10. import CesiumMath from "./Math.js";
  11. import OrientedBoundingBox from "./OrientedBoundingBox.js";
  12. import QuantizedMeshTerrainData from "./QuantizedMeshTerrainData.js";
  13. import Rectangle from "./Rectangle.js";
  14. import TaskProcessor from "./TaskProcessor.js";
  15. import TerrainEncoding from "./TerrainEncoding.js";
  16. import TerrainMesh from "./TerrainMesh.js";
  17. /**
  18. * Terrain data for a single tile from a Google Earth Enterprise server.
  19. *
  20. * @alias GoogleEarthEnterpriseTerrainData
  21. * @constructor
  22. *
  23. * @param {Object} options Object with the following properties:
  24. * @param {ArrayBuffer} options.buffer The buffer containing terrain data.
  25. * @param {Number} options.negativeAltitudeExponentBias Multiplier for negative terrain heights that are encoded as very small positive values.
  26. * @param {Number} options.negativeElevationThreshold Threshold for negative values
  27. * @param {Number} [options.childTileMask=15] A bit mask indicating which of this tile's four children exist.
  28. * If a child's bit is set, geometry will be requested for that tile as well when it
  29. * is needed. If the bit is cleared, the child tile is not requested and geometry is
  30. * instead upsampled from the parent. The bit values are as follows:
  31. * <table>
  32. * <tr><th>Bit Position</th><th>Bit Value</th><th>Child Tile</th></tr>
  33. * <tr><td>0</td><td>1</td><td>Southwest</td></tr>
  34. * <tr><td>1</td><td>2</td><td>Southeast</td></tr>
  35. * <tr><td>2</td><td>4</td><td>Northeast</td></tr>
  36. * <tr><td>3</td><td>8</td><td>Northwest</td></tr>
  37. * </table>
  38. * @param {Boolean} [options.createdByUpsampling=false] True if this instance was created by upsampling another instance;
  39. * otherwise, false.
  40. * @param {Credit[]} [options.credits] Array of credits for this tile.
  41. *
  42. *
  43. * @example
  44. * var buffer = ...
  45. * var childTileMask = ...
  46. * var terrainData = new Cesium.GoogleEarthEnterpriseTerrainData({
  47. * buffer : heightBuffer,
  48. * childTileMask : childTileMask
  49. * });
  50. *
  51. * @see TerrainData
  52. * @see HeightmapTerrainData
  53. * @see QuantizedMeshTerrainData
  54. */
  55. function GoogleEarthEnterpriseTerrainData(options) {
  56. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  57. //>>includeStart('debug', pragmas.debug);
  58. Check.typeOf.object("options.buffer", options.buffer);
  59. Check.typeOf.number(
  60. "options.negativeAltitudeExponentBias",
  61. options.negativeAltitudeExponentBias
  62. );
  63. Check.typeOf.number(
  64. "options.negativeElevationThreshold",
  65. options.negativeElevationThreshold
  66. );
  67. //>>includeEnd('debug');
  68. this._buffer = options.buffer;
  69. this._credits = options.credits;
  70. this._negativeAltitudeExponentBias = options.negativeAltitudeExponentBias;
  71. this._negativeElevationThreshold = options.negativeElevationThreshold;
  72. // Convert from google layout to layout of other providers
  73. // 3 2 -> 2 3
  74. // 0 1 -> 0 1
  75. var googleChildTileMask = defaultValue(options.childTileMask, 15);
  76. var childTileMask = googleChildTileMask & 3; // Bottom row is identical
  77. childTileMask |= googleChildTileMask & 4 ? 8 : 0; // NE
  78. childTileMask |= googleChildTileMask & 8 ? 4 : 0; // NW
  79. this._childTileMask = childTileMask;
  80. this._createdByUpsampling = defaultValue(options.createdByUpsampling, false);
  81. this._skirtHeight = undefined;
  82. this._bufferType = this._buffer.constructor;
  83. this._mesh = undefined;
  84. this._minimumHeight = undefined;
  85. this._maximumHeight = undefined;
  86. }
  87. Object.defineProperties(GoogleEarthEnterpriseTerrainData.prototype, {
  88. /**
  89. * An array of credits for this tile
  90. * @memberof GoogleEarthEnterpriseTerrainData.prototype
  91. * @type {Credit[]}
  92. */
  93. credits: {
  94. get: function () {
  95. return this._credits;
  96. },
  97. },
  98. /**
  99. * The water mask included in this terrain data, if any. A water mask is a rectangular
  100. * Uint8Array or image where a value of 255 indicates water and a value of 0 indicates land.
  101. * Values in between 0 and 255 are allowed as well to smoothly blend between land and water.
  102. * @memberof GoogleEarthEnterpriseTerrainData.prototype
  103. * @type {Uint8Array|HTMLImageElement|HTMLCanvasElement}
  104. */
  105. waterMask: {
  106. get: function () {
  107. return undefined;
  108. },
  109. },
  110. });
  111. var taskProcessor = new TaskProcessor(
  112. "createVerticesFromGoogleEarthEnterpriseBuffer"
  113. );
  114. var nativeRectangleScratch = new Rectangle();
  115. var rectangleScratch = new Rectangle();
  116. /**
  117. * Creates a {@link TerrainMesh} from this terrain data.
  118. *
  119. * @private
  120. *
  121. * @param {TilingScheme} tilingScheme The tiling scheme to which this tile belongs.
  122. * @param {Number} x The X coordinate of the tile for which to create the terrain data.
  123. * @param {Number} y The Y coordinate of the tile for which to create the terrain data.
  124. * @param {Number} level The level of the tile for which to create the terrain data.
  125. * @param {Number} [exaggeration=1.0] The scale used to exaggerate the terrain.
  126. * @returns {Promise.<TerrainMesh>|undefined} A promise for the terrain mesh, or undefined if too many
  127. * asynchronous mesh creations are already in progress and the operation should
  128. * be retried later.
  129. */
  130. GoogleEarthEnterpriseTerrainData.prototype.createMesh = function (
  131. tilingScheme,
  132. x,
  133. y,
  134. level,
  135. exaggeration
  136. ) {
  137. //>>includeStart('debug', pragmas.debug);
  138. Check.typeOf.object("tilingScheme", tilingScheme);
  139. Check.typeOf.number("x", x);
  140. Check.typeOf.number("y", y);
  141. Check.typeOf.number("level", level);
  142. //>>includeEnd('debug');
  143. var ellipsoid = tilingScheme.ellipsoid;
  144. tilingScheme.tileXYToNativeRectangle(x, y, level, nativeRectangleScratch);
  145. tilingScheme.tileXYToRectangle(x, y, level, rectangleScratch);
  146. exaggeration = defaultValue(exaggeration, 1.0);
  147. // Compute the center of the tile for RTC rendering.
  148. var center = ellipsoid.cartographicToCartesian(
  149. Rectangle.center(rectangleScratch)
  150. );
  151. var levelZeroMaxError = 40075.16; // From Google's Doc
  152. var thisLevelMaxError = levelZeroMaxError / (1 << level);
  153. this._skirtHeight = Math.min(thisLevelMaxError * 8.0, 1000.0);
  154. var verticesPromise = taskProcessor.scheduleTask({
  155. buffer: this._buffer,
  156. nativeRectangle: nativeRectangleScratch,
  157. rectangle: rectangleScratch,
  158. relativeToCenter: center,
  159. ellipsoid: ellipsoid,
  160. skirtHeight: this._skirtHeight,
  161. exaggeration: exaggeration,
  162. includeWebMercatorT: true,
  163. negativeAltitudeExponentBias: this._negativeAltitudeExponentBias,
  164. negativeElevationThreshold: this._negativeElevationThreshold,
  165. });
  166. if (!defined(verticesPromise)) {
  167. // Postponed
  168. return undefined;
  169. }
  170. var that = this;
  171. return verticesPromise.then(function (result) {
  172. // Clone complex result objects because the transfer from the web worker
  173. // has stripped them down to JSON-style objects.
  174. that._mesh = new TerrainMesh(
  175. center,
  176. new Float32Array(result.vertices),
  177. new Uint16Array(result.indices),
  178. result.indexCountWithoutSkirts,
  179. result.vertexCountWithoutSkirts,
  180. result.minimumHeight,
  181. result.maximumHeight,
  182. BoundingSphere.clone(result.boundingSphere3D),
  183. Cartesian3.clone(result.occludeePointInScaledSpace),
  184. result.numberOfAttributes,
  185. OrientedBoundingBox.clone(result.orientedBoundingBox),
  186. TerrainEncoding.clone(result.encoding),
  187. exaggeration,
  188. result.westIndicesSouthToNorth,
  189. result.southIndicesEastToWest,
  190. result.eastIndicesNorthToSouth,
  191. result.northIndicesWestToEast
  192. );
  193. that._minimumHeight = result.minimumHeight;
  194. that._maximumHeight = result.maximumHeight;
  195. // Free memory received from server after mesh is created.
  196. that._buffer = undefined;
  197. return that._mesh;
  198. });
  199. };
  200. /**
  201. * Computes the terrain height at a specified longitude and latitude.
  202. *
  203. * @param {Rectangle} rectangle The rectangle covered by this terrain data.
  204. * @param {Number} longitude The longitude in radians.
  205. * @param {Number} latitude The latitude in radians.
  206. * @returns {Number} The terrain height at the specified position. If the position
  207. * is outside the rectangle, this method will extrapolate the height, which is likely to be wildly
  208. * incorrect for positions far outside the rectangle.
  209. */
  210. GoogleEarthEnterpriseTerrainData.prototype.interpolateHeight = function (
  211. rectangle,
  212. longitude,
  213. latitude
  214. ) {
  215. var u = CesiumMath.clamp(
  216. (longitude - rectangle.west) / rectangle.width,
  217. 0.0,
  218. 1.0
  219. );
  220. var v = CesiumMath.clamp(
  221. (latitude - rectangle.south) / rectangle.height,
  222. 0.0,
  223. 1.0
  224. );
  225. if (!defined(this._mesh)) {
  226. return interpolateHeight(this, u, v, rectangle);
  227. }
  228. return interpolateMeshHeight(this, u, v);
  229. };
  230. var upsampleTaskProcessor = new TaskProcessor("upsampleQuantizedTerrainMesh");
  231. /**
  232. * Upsamples this terrain data for use by a descendant tile. The resulting instance will contain a subset of the
  233. * height samples in this instance, interpolated if necessary.
  234. *
  235. * @param {TilingScheme} tilingScheme The tiling scheme of this terrain data.
  236. * @param {Number} thisX The X coordinate of this tile in the tiling scheme.
  237. * @param {Number} thisY The Y coordinate of this tile in the tiling scheme.
  238. * @param {Number} thisLevel The level of this tile in the tiling scheme.
  239. * @param {Number} descendantX The X coordinate within the tiling scheme of the descendant tile for which we are upsampling.
  240. * @param {Number} descendantY The Y coordinate within the tiling scheme of the descendant tile for which we are upsampling.
  241. * @param {Number} descendantLevel The level within the tiling scheme of the descendant tile for which we are upsampling.
  242. * @returns {Promise.<HeightmapTerrainData>|undefined} A promise for upsampled heightmap terrain data for the descendant tile,
  243. * or undefined if too many asynchronous upsample operations are in progress and the request has been
  244. * deferred.
  245. */
  246. GoogleEarthEnterpriseTerrainData.prototype.upsample = function (
  247. tilingScheme,
  248. thisX,
  249. thisY,
  250. thisLevel,
  251. descendantX,
  252. descendantY,
  253. descendantLevel
  254. ) {
  255. //>>includeStart('debug', pragmas.debug);
  256. Check.typeOf.object("tilingScheme", tilingScheme);
  257. Check.typeOf.number("thisX", thisX);
  258. Check.typeOf.number("thisY", thisY);
  259. Check.typeOf.number("thisLevel", thisLevel);
  260. Check.typeOf.number("descendantX", descendantX);
  261. Check.typeOf.number("descendantY", descendantY);
  262. Check.typeOf.number("descendantLevel", descendantLevel);
  263. var levelDifference = descendantLevel - thisLevel;
  264. if (levelDifference > 1) {
  265. throw new DeveloperError(
  266. "Upsampling through more than one level at a time is not currently supported."
  267. );
  268. }
  269. //>>includeEnd('debug');
  270. var mesh = this._mesh;
  271. if (!defined(this._mesh)) {
  272. return undefined;
  273. }
  274. var isEastChild = thisX * 2 !== descendantX;
  275. var isNorthChild = thisY * 2 === descendantY;
  276. var ellipsoid = tilingScheme.ellipsoid;
  277. var childRectangle = tilingScheme.tileXYToRectangle(
  278. descendantX,
  279. descendantY,
  280. descendantLevel
  281. );
  282. var upsamplePromise = upsampleTaskProcessor.scheduleTask({
  283. vertices: mesh.vertices,
  284. indices: mesh.indices,
  285. indexCountWithoutSkirts: mesh.indexCountWithoutSkirts,
  286. vertexCountWithoutSkirts: mesh.vertexCountWithoutSkirts,
  287. encoding: mesh.encoding,
  288. minimumHeight: this._minimumHeight,
  289. maximumHeight: this._maximumHeight,
  290. isEastChild: isEastChild,
  291. isNorthChild: isNorthChild,
  292. childRectangle: childRectangle,
  293. ellipsoid: ellipsoid,
  294. exaggeration: mesh.exaggeration,
  295. });
  296. if (!defined(upsamplePromise)) {
  297. // Postponed
  298. return undefined;
  299. }
  300. var that = this;
  301. return upsamplePromise.then(function (result) {
  302. var quantizedVertices = new Uint16Array(result.vertices);
  303. var indicesTypedArray = IndexDatatype.createTypedArray(
  304. quantizedVertices.length / 3,
  305. result.indices
  306. );
  307. var skirtHeight = that._skirtHeight;
  308. // Use QuantizedMeshTerrainData since we have what we need already parsed
  309. return new QuantizedMeshTerrainData({
  310. quantizedVertices: quantizedVertices,
  311. indices: indicesTypedArray,
  312. minimumHeight: result.minimumHeight,
  313. maximumHeight: result.maximumHeight,
  314. boundingSphere: BoundingSphere.clone(result.boundingSphere),
  315. orientedBoundingBox: OrientedBoundingBox.clone(
  316. result.orientedBoundingBox
  317. ),
  318. horizonOcclusionPoint: Cartesian3.clone(result.horizonOcclusionPoint),
  319. westIndices: result.westIndices,
  320. southIndices: result.southIndices,
  321. eastIndices: result.eastIndices,
  322. northIndices: result.northIndices,
  323. westSkirtHeight: skirtHeight,
  324. southSkirtHeight: skirtHeight,
  325. eastSkirtHeight: skirtHeight,
  326. northSkirtHeight: skirtHeight,
  327. childTileMask: 0,
  328. createdByUpsampling: true,
  329. credits: that._credits,
  330. });
  331. });
  332. };
  333. /**
  334. * Determines if a given child tile is available, based on the
  335. * {@link HeightmapTerrainData.childTileMask}. The given child tile coordinates are assumed
  336. * to be one of the four children of this tile. If non-child tile coordinates are
  337. * given, the availability of the southeast child tile is returned.
  338. *
  339. * @param {Number} thisX The tile X coordinate of this (the parent) tile.
  340. * @param {Number} thisY The tile Y coordinate of this (the parent) tile.
  341. * @param {Number} childX The tile X coordinate of the child tile to check for availability.
  342. * @param {Number} childY The tile Y coordinate of the child tile to check for availability.
  343. * @returns {Boolean} True if the child tile is available; otherwise, false.
  344. */
  345. GoogleEarthEnterpriseTerrainData.prototype.isChildAvailable = function (
  346. thisX,
  347. thisY,
  348. childX,
  349. childY
  350. ) {
  351. //>>includeStart('debug', pragmas.debug);
  352. Check.typeOf.number("thisX", thisX);
  353. Check.typeOf.number("thisY", thisY);
  354. Check.typeOf.number("childX", childX);
  355. Check.typeOf.number("childY", childY);
  356. //>>includeEnd('debug');
  357. var bitNumber = 2; // northwest child
  358. if (childX !== thisX * 2) {
  359. ++bitNumber; // east child
  360. }
  361. if (childY !== thisY * 2) {
  362. bitNumber -= 2; // south child
  363. }
  364. return (this._childTileMask & (1 << bitNumber)) !== 0;
  365. };
  366. /**
  367. * Gets a value indicating whether or not this terrain data was created by upsampling lower resolution
  368. * terrain data. If this value is false, the data was obtained from some other source, such
  369. * as by downloading it from a remote server. This method should return true for instances
  370. * returned from a call to {@link HeightmapTerrainData#upsample}.
  371. *
  372. * @returns {Boolean} True if this instance was created by upsampling; otherwise, false.
  373. */
  374. GoogleEarthEnterpriseTerrainData.prototype.wasCreatedByUpsampling = function () {
  375. return this._createdByUpsampling;
  376. };
  377. var texCoordScratch0 = new Cartesian2();
  378. var texCoordScratch1 = new Cartesian2();
  379. var texCoordScratch2 = new Cartesian2();
  380. var barycentricCoordinateScratch = new Cartesian3();
  381. function interpolateMeshHeight(terrainData, u, v) {
  382. var mesh = terrainData._mesh;
  383. var vertices = mesh.vertices;
  384. var encoding = mesh.encoding;
  385. var indices = mesh.indices;
  386. for (var i = 0, len = indices.length; i < len; i += 3) {
  387. var i0 = indices[i];
  388. var i1 = indices[i + 1];
  389. var i2 = indices[i + 2];
  390. var uv0 = encoding.decodeTextureCoordinates(vertices, i0, texCoordScratch0);
  391. var uv1 = encoding.decodeTextureCoordinates(vertices, i1, texCoordScratch1);
  392. var uv2 = encoding.decodeTextureCoordinates(vertices, i2, texCoordScratch2);
  393. var barycentric = Intersections2D.computeBarycentricCoordinates(
  394. u,
  395. v,
  396. uv0.x,
  397. uv0.y,
  398. uv1.x,
  399. uv1.y,
  400. uv2.x,
  401. uv2.y,
  402. barycentricCoordinateScratch
  403. );
  404. if (
  405. barycentric.x >= -1e-15 &&
  406. barycentric.y >= -1e-15 &&
  407. barycentric.z >= -1e-15
  408. ) {
  409. var h0 = encoding.decodeHeight(vertices, i0);
  410. var h1 = encoding.decodeHeight(vertices, i1);
  411. var h2 = encoding.decodeHeight(vertices, i2);
  412. return barycentric.x * h0 + barycentric.y * h1 + barycentric.z * h2;
  413. }
  414. }
  415. // Position does not lie in any triangle in this mesh.
  416. return undefined;
  417. }
  418. var sizeOfUint16 = Uint16Array.BYTES_PER_ELEMENT;
  419. var sizeOfUint32 = Uint32Array.BYTES_PER_ELEMENT;
  420. var sizeOfInt32 = Int32Array.BYTES_PER_ELEMENT;
  421. var sizeOfFloat = Float32Array.BYTES_PER_ELEMENT;
  422. var sizeOfDouble = Float64Array.BYTES_PER_ELEMENT;
  423. function interpolateHeight(terrainData, u, v, rectangle) {
  424. var buffer = terrainData._buffer;
  425. var quad = 0; // SW
  426. var uStart = 0.0;
  427. var vStart = 0.0;
  428. if (v > 0.5) {
  429. // Upper row
  430. if (u > 0.5) {
  431. // NE
  432. quad = 2;
  433. uStart = 0.5;
  434. } else {
  435. // NW
  436. quad = 3;
  437. }
  438. vStart = 0.5;
  439. } else if (u > 0.5) {
  440. // SE
  441. quad = 1;
  442. uStart = 0.5;
  443. }
  444. var dv = new DataView(buffer);
  445. var offset = 0;
  446. for (var q = 0; q < quad; ++q) {
  447. offset += dv.getUint32(offset, true);
  448. offset += sizeOfUint32;
  449. }
  450. offset += sizeOfUint32; // Skip length of quad
  451. offset += 2 * sizeOfDouble; // Skip origin
  452. // Read sizes
  453. var xSize = CesiumMath.toRadians(dv.getFloat64(offset, true) * 180.0);
  454. offset += sizeOfDouble;
  455. var ySize = CesiumMath.toRadians(dv.getFloat64(offset, true) * 180.0);
  456. offset += sizeOfDouble;
  457. // Samples per quad
  458. var xScale = rectangle.width / xSize / 2;
  459. var yScale = rectangle.height / ySize / 2;
  460. // Number of points
  461. var numPoints = dv.getInt32(offset, true);
  462. offset += sizeOfInt32;
  463. // Number of faces
  464. var numIndices = dv.getInt32(offset, true) * 3;
  465. offset += sizeOfInt32;
  466. offset += sizeOfInt32; // Skip Level
  467. var uBuffer = new Array(numPoints);
  468. var vBuffer = new Array(numPoints);
  469. var heights = new Array(numPoints);
  470. var i;
  471. for (i = 0; i < numPoints; ++i) {
  472. uBuffer[i] = uStart + dv.getUint8(offset++) * xScale;
  473. vBuffer[i] = vStart + dv.getUint8(offset++) * yScale;
  474. // Height is stored in units of (1/EarthRadius) or (1/6371010.0)
  475. heights[i] = dv.getFloat32(offset, true) * 6371010.0;
  476. offset += sizeOfFloat;
  477. }
  478. var indices = new Array(numIndices);
  479. for (i = 0; i < numIndices; ++i) {
  480. indices[i] = dv.getUint16(offset, true);
  481. offset += sizeOfUint16;
  482. }
  483. for (i = 0; i < numIndices; i += 3) {
  484. var i0 = indices[i];
  485. var i1 = indices[i + 1];
  486. var i2 = indices[i + 2];
  487. var u0 = uBuffer[i0];
  488. var u1 = uBuffer[i1];
  489. var u2 = uBuffer[i2];
  490. var v0 = vBuffer[i0];
  491. var v1 = vBuffer[i1];
  492. var v2 = vBuffer[i2];
  493. var barycentric = Intersections2D.computeBarycentricCoordinates(
  494. u,
  495. v,
  496. u0,
  497. v0,
  498. u1,
  499. v1,
  500. u2,
  501. v2,
  502. barycentricCoordinateScratch
  503. );
  504. if (
  505. barycentric.x >= -1e-15 &&
  506. barycentric.y >= -1e-15 &&
  507. barycentric.z >= -1e-15
  508. ) {
  509. return (
  510. barycentric.x * heights[i0] +
  511. barycentric.y * heights[i1] +
  512. barycentric.z * heights[i2]
  513. );
  514. }
  515. }
  516. // Position does not lie in any triangle in this mesh.
  517. return undefined;
  518. }
  519. export default GoogleEarthEnterpriseTerrainData;