createVerticesFromQuantizedTerrainMesh.js 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843
  1. /**
  2. * Cesium - https://github.com/AnalyticalGraphicsInc/cesium
  3. *
  4. * Copyright 2011-2017 Cesium Contributors
  5. *
  6. * Licensed under the Apache License, Version 2.0 (the "License");
  7. * you may not use this file except in compliance with the License.
  8. * You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. *
  18. * Columbus View (Pat. Pend.)
  19. *
  20. * Portions licensed separately.
  21. * See https://github.com/AnalyticalGraphicsInc/cesium/blob/master/LICENSE.md for full licensing details.
  22. */
  23. define(['./when-8d13db60', './Check-70bec281', './Math-61ede240', './Cartographic-fe4be337', './Cartesian2-85064f09', './BoundingSphere-775c5788', './Cartesian4-5af5bb24', './RuntimeError-ba10bc3e', './WebGLConstants-4c11ee5f', './ComponentDatatype-5862616f', './FeatureDetection-7bd32c34', './Transforms-b2e71640', './buildModuleUrl-14bfe498', './AttributeCompression-84a90a13', './IndexDatatype-9435b55f', './IntersectionTests-397d9494', './Plane-8390418f', './WebMercatorProjection-80c70558', './createTaskProcessorWorker', './EllipsoidTangentPlane-a815c96f', './OrientedBoundingBox-635e6e10', './TerrainEncoding-a807a704'], function (when, Check, _Math, Cartographic, Cartesian2, BoundingSphere, Cartesian4, RuntimeError, WebGLConstants, ComponentDatatype, FeatureDetection, Transforms, buildModuleUrl, AttributeCompression, IndexDatatype, IntersectionTests, Plane, WebMercatorProjection, createTaskProcessorWorker, EllipsoidTangentPlane, OrientedBoundingBox, TerrainEncoding) { 'use strict';
  24. /**
  25. * Provides terrain or other geometry for the surface of an ellipsoid. The surface geometry is
  26. * organized into a pyramid of tiles according to a {@link TilingScheme}. This type describes an
  27. * interface and is not intended to be instantiated directly.
  28. *
  29. * @alias TerrainProvider
  30. * @constructor
  31. *
  32. * @see EllipsoidTerrainProvider
  33. * @see CesiumTerrainProvider
  34. * @see VRTheWorldTerrainProvider
  35. * @see GoogleEarthEnterpriseTerrainProvider
  36. */
  37. function TerrainProvider() {
  38. Check.DeveloperError.throwInstantiationError();
  39. }
  40. Object.defineProperties(TerrainProvider.prototype, {
  41. /**
  42. * Gets an event that is raised when the terrain provider encounters an asynchronous error.. By subscribing
  43. * to the event, you will be notified of the error and can potentially recover from it. Event listeners
  44. * are passed an instance of {@link TileProviderError}.
  45. * @memberof TerrainProvider.prototype
  46. * @type {Event}
  47. */
  48. errorEvent : {
  49. get : Check.DeveloperError.throwInstantiationError
  50. },
  51. /**
  52. * Gets the credit to display when this terrain provider is active. Typically this is used to credit
  53. * the source of the terrain. This function should
  54. * not be called before {@link TerrainProvider#ready} returns true.
  55. * @memberof TerrainProvider.prototype
  56. * @type {Credit}
  57. */
  58. credit : {
  59. get : Check.DeveloperError.throwInstantiationError
  60. },
  61. /**
  62. * Gets the tiling scheme used by the provider. This function should
  63. * not be called before {@link TerrainProvider#ready} returns true.
  64. * @memberof TerrainProvider.prototype
  65. * @type {TilingScheme}
  66. */
  67. tilingScheme : {
  68. get : Check.DeveloperError.throwInstantiationError
  69. },
  70. /**
  71. * Gets a value indicating whether or not the provider is ready for use.
  72. * @memberof TerrainProvider.prototype
  73. * @type {Boolean}
  74. */
  75. ready : {
  76. get : Check.DeveloperError.throwInstantiationError
  77. },
  78. /**
  79. * Gets a promise that resolves to true when the provider is ready for use.
  80. * @memberof TerrainProvider.prototype
  81. * @type {Promise.<Boolean>}
  82. * @readonly
  83. */
  84. readyPromise : {
  85. get : Check.DeveloperError.throwInstantiationError
  86. },
  87. /**
  88. * Gets a value indicating whether or not the provider includes a water mask. The water mask
  89. * indicates which areas of the globe are water rather than land, so they can be rendered
  90. * as a reflective surface with animated waves. This function should not be
  91. * called before {@link TerrainProvider#ready} returns true.
  92. * @memberof TerrainProvider.prototype
  93. * @type {Boolean}
  94. */
  95. hasWaterMask : {
  96. get : Check.DeveloperError.throwInstantiationError
  97. },
  98. /**
  99. * Gets a value indicating whether or not the requested tiles include vertex normals.
  100. * This function should not be called before {@link TerrainProvider#ready} returns true.
  101. * @memberof TerrainProvider.prototype
  102. * @type {Boolean}
  103. */
  104. hasVertexNormals : {
  105. get : Check.DeveloperError.throwInstantiationError
  106. },
  107. /**
  108. * Gets an object that can be used to determine availability of terrain from this provider, such as
  109. * at points and in rectangles. This function should not be called before
  110. * {@link TerrainProvider#ready} returns true. This property may be undefined if availability
  111. * information is not available.
  112. * @memberof TerrainProvider.prototype
  113. * @type {TileAvailability}
  114. */
  115. availability : {
  116. get : Check.DeveloperError.throwInstantiationError
  117. }
  118. });
  119. var regularGridIndicesCache = [];
  120. /**
  121. * Gets a list of indices for a triangle mesh representing a regular grid. Calling
  122. * this function multiple times with the same grid width and height returns the
  123. * same list of indices. The total number of vertices must be less than or equal
  124. * to 65536.
  125. *
  126. * @param {Number} width The number of vertices in the regular grid in the horizontal direction.
  127. * @param {Number} height The number of vertices in the regular grid in the vertical direction.
  128. * @returns {Uint16Array|Uint32Array} The list of indices. Uint16Array gets returned for 64KB or less and Uint32Array for 4GB or less.
  129. */
  130. TerrainProvider.getRegularGridIndices = function(width, height) {
  131. //>>includeStart('debug', pragmas.debug);
  132. if (width * height >= _Math.CesiumMath.FOUR_GIGABYTES) {
  133. throw new Check.DeveloperError('The total number of vertices (width * height) must be less than 4,294,967,296.');
  134. }
  135. //>>includeEnd('debug');
  136. var byWidth = regularGridIndicesCache[width];
  137. if (!when.defined(byWidth)) {
  138. regularGridIndicesCache[width] = byWidth = [];
  139. }
  140. var indices = byWidth[height];
  141. if (!when.defined(indices)) {
  142. if (width * height < _Math.CesiumMath.SIXTY_FOUR_KILOBYTES) {
  143. indices = byWidth[height] = new Uint16Array((width - 1) * (height - 1) * 6 + 3*(width + height - 2));
  144. } else {
  145. indices = byWidth[height] = new Uint32Array((width - 1) * (height - 1) * 6 + 3*(width + height - 2));
  146. }
  147. addRegularGridIndices(width, height, indices, 0);
  148. }
  149. return indices;
  150. };
  151. TerrainProvider.getRegularGridIndicesForReproject = function(width, height) {
  152. //>>includeStart('debug', pragmas.debug);
  153. if (width * height >= _Math.CesiumMath.FOUR_GIGABYTES) {
  154. throw new Check.DeveloperError('The total number of vertices (width * height) must be less than 4,294,967,296.');
  155. }
  156. //>>includeEnd('debug');
  157. var byWidth = regularGridIndicesCache[width];
  158. if (!when.defined(byWidth)) {
  159. regularGridIndicesCache[width] = byWidth = [];
  160. }
  161. var indices = byWidth[height];
  162. if (!when.defined(indices)) {
  163. if (width * height < _Math.CesiumMath.SIXTY_FOUR_KILOBYTES) {
  164. indices = byWidth[height] = new Uint16Array((width - 1) * (height - 1) * 6);
  165. } else {
  166. indices = byWidth[height] = new Uint32Array((width - 1) * (height - 1) * 6);
  167. }
  168. addRegularGridIndices(width, height, indices, 0);
  169. }
  170. return indices;
  171. };
  172. var regularGridAndEdgeIndicesCache = [];
  173. /**
  174. * @private
  175. */
  176. TerrainProvider.getRegularGridIndicesAndEdgeIndices = function(width, height) {
  177. //>>includeStart('debug', pragmas.debug);
  178. if (width * height >= _Math.CesiumMath.FOUR_GIGABYTES) {
  179. throw new Check.DeveloperError('The total number of vertices (width * height) must be less than 4,294,967,296.');
  180. }
  181. //>>includeEnd('debug');
  182. var byWidth = regularGridAndEdgeIndicesCache[width];
  183. if (!when.defined(byWidth)) {
  184. regularGridAndEdgeIndicesCache[width] = byWidth = [];
  185. }
  186. var indicesAndEdges = byWidth[height];
  187. if (!when.defined(indicesAndEdges)) {
  188. var indices = TerrainProvider.getRegularGridIndices(width, height);
  189. var edgeIndices = getEdgeIndices(width, height);
  190. var westIndicesSouthToNorth = edgeIndices.westIndicesSouthToNorth;
  191. var southIndicesEastToWest = edgeIndices.southIndicesEastToWest;
  192. var eastIndicesNorthToSouth = edgeIndices.eastIndicesNorthToSouth;
  193. var northIndicesWestToEast = edgeIndices.northIndicesWestToEast;
  194. indicesAndEdges = byWidth[height] = {
  195. indices : indices,
  196. westIndicesSouthToNorth : westIndicesSouthToNorth,
  197. southIndicesEastToWest : southIndicesEastToWest,
  198. eastIndicesNorthToSouth : eastIndicesNorthToSouth,
  199. northIndicesWestToEast : northIndicesWestToEast
  200. };
  201. }
  202. return indicesAndEdges;
  203. };
  204. var regularGridAndSkirtAndEdgeIndicesCache = [];
  205. /**
  206. * @private
  207. */
  208. TerrainProvider.getRegularGridAndSkirtIndicesAndEdgeIndices = function(width, height) {
  209. //>>includeStart('debug', pragmas.debug);
  210. if (width * height >= _Math.CesiumMath.FOUR_GIGABYTES) {
  211. throw new Check.DeveloperError('The total number of vertices (width * height) must be less than 4,294,967,296.');
  212. }
  213. //>>includeEnd('debug');
  214. var byWidth = regularGridAndSkirtAndEdgeIndicesCache[width];
  215. if (!when.defined(byWidth)) {
  216. regularGridAndSkirtAndEdgeIndicesCache[width] = byWidth = [];
  217. }
  218. var indicesAndEdges = byWidth[height];
  219. if (!when.defined(indicesAndEdges)) {
  220. var gridVertexCount = width * height;
  221. var gridIndexCount = (width - 1) * (height - 1) * 6;
  222. var edgeVertexCount = width * 2 + height * 2;
  223. var edgeIndexCount = Math.max(0, edgeVertexCount - 4) * 6;
  224. var vertexCount = gridVertexCount + edgeVertexCount;
  225. var boundaryIndexCount = 3*(width + height - 2);
  226. var indexCount = gridIndexCount + edgeIndexCount + boundaryIndexCount;
  227. var edgeIndices = getEdgeIndices(width, height);
  228. var westIndicesSouthToNorth = edgeIndices.westIndicesSouthToNorth;
  229. var southIndicesEastToWest = edgeIndices.southIndicesEastToWest;
  230. var eastIndicesNorthToSouth = edgeIndices.eastIndicesNorthToSouth;
  231. var northIndicesWestToEast = edgeIndices.northIndicesWestToEast;
  232. var indices = IndexDatatype.IndexDatatype.createTypedArray(vertexCount, indexCount);
  233. addRegularGridIndices(width, height, indices, 0);
  234. TerrainProvider.addSkirtIndices(westIndicesSouthToNorth, southIndicesEastToWest, eastIndicesNorthToSouth, northIndicesWestToEast, gridVertexCount, indices, gridIndexCount + boundaryIndexCount);
  235. indicesAndEdges = byWidth[height] = {
  236. indices : indices,
  237. westIndicesSouthToNorth : westIndicesSouthToNorth,
  238. southIndicesEastToWest : southIndicesEastToWest,
  239. eastIndicesNorthToSouth : eastIndicesNorthToSouth,
  240. northIndicesWestToEast : northIndicesWestToEast,
  241. indexCountWithoutSkirts : gridIndexCount
  242. };
  243. }
  244. return indicesAndEdges;
  245. };
  246. /**
  247. * @private
  248. */
  249. TerrainProvider.addSkirtIndices = function(westIndicesSouthToNorth, southIndicesEastToWest, eastIndicesNorthToSouth, northIndicesWestToEast, vertexCount, indices, offset, edgeMap) {
  250. var vertexIndex = vertexCount;
  251. offset = addSkirtIndices(westIndicesSouthToNorth, vertexIndex, indices, offset, edgeMap);
  252. vertexIndex += westIndicesSouthToNorth.length;
  253. offset = addSkirtIndices(southIndicesEastToWest, vertexIndex, indices, offset, edgeMap);
  254. vertexIndex += southIndicesEastToWest.length;
  255. offset = addSkirtIndices(eastIndicesNorthToSouth, vertexIndex, indices, offset, edgeMap);
  256. vertexIndex += eastIndicesNorthToSouth.length;
  257. addSkirtIndices(northIndicesWestToEast, vertexIndex, indices, offset, edgeMap);
  258. };
  259. function getEdgeIndices(width, height) {
  260. var westIndicesSouthToNorth = new Array(height);
  261. var southIndicesEastToWest = new Array(width);
  262. var eastIndicesNorthToSouth = new Array(height);
  263. var northIndicesWestToEast = new Array(width);
  264. var i;
  265. for (i = 0; i < width; ++i) {
  266. northIndicesWestToEast[i] = i;
  267. southIndicesEastToWest[i] = width * height - 1 - i;
  268. }
  269. for (i = 0; i < height; ++i) {
  270. eastIndicesNorthToSouth[i] = (i + 1) * width - 1;
  271. westIndicesSouthToNorth[i] = (height - i - 1) * width;
  272. }
  273. return {
  274. westIndicesSouthToNorth : westIndicesSouthToNorth,
  275. southIndicesEastToWest : southIndicesEastToWest,
  276. eastIndicesNorthToSouth : eastIndicesNorthToSouth,
  277. northIndicesWestToEast : northIndicesWestToEast
  278. };
  279. }
  280. function addRegularGridIndices(width, height, indices, offset) {
  281. var index = 0;
  282. for (var j = 0; j < height - 1; ++j) {
  283. for (var i = 0; i < width - 1; ++i) {
  284. var upperLeft = index;
  285. var lowerLeft = upperLeft + width;
  286. var lowerRight = lowerLeft + 1;
  287. var upperRight = upperLeft + 1;
  288. indices[offset++] = upperLeft;
  289. indices[offset++] = lowerLeft;
  290. indices[offset++] = upperRight;
  291. indices[offset++] = upperRight;
  292. indices[offset++] = lowerLeft;
  293. indices[offset++] = lowerRight;
  294. ++index;
  295. }
  296. ++index;
  297. }
  298. var boundaryHeight = (height - 1)/2;
  299. var boundaryWidth = (width - 1)/2;
  300. index = 0;
  301. for(var i=0; i<boundaryWidth; i++)
  302. {
  303. indices[offset++] = index;
  304. indices[offset++] = index + 1;
  305. indices[offset++] = index + 2;
  306. index+=2;
  307. }
  308. index = width * (height - 1);
  309. for(var i=0; i<boundaryWidth; i++)
  310. {
  311. indices[offset++] = index + 1;
  312. indices[offset++] = index;
  313. indices[offset++] = index + 2;
  314. index+=2;
  315. }
  316. index = 0;
  317. for(var i=0; i<boundaryHeight; i++)
  318. {
  319. indices[offset++] = index + width;
  320. indices[offset++] = index;
  321. indices[offset++] = index + 2*width;
  322. index+=2*width;
  323. }
  324. index = width - 1;
  325. for(var i=0; i<boundaryHeight; i++)
  326. {
  327. indices[offset++] = index;
  328. indices[offset++] = index + width;
  329. indices[offset++] = index + 2*width;
  330. index+=2*width;
  331. }
  332. }
  333. function addSkirtIndices(edgeIndices, vertexIndex, indices, offset, edgeMap) {
  334. var hasEdgeMap = when.defined(edgeMap);
  335. var previousIndex = edgeIndices[0];
  336. var length = edgeIndices.length;
  337. for (var i = 1; i < length; ++i) {
  338. var index = edgeIndices[i];
  339. if(hasEdgeMap && !edgeMap[previousIndex + '_' + index]){
  340. continue ;
  341. }
  342. indices[offset++] = previousIndex;
  343. indices[offset++] = index;
  344. indices[offset++] = vertexIndex;
  345. indices[offset++] = vertexIndex;
  346. indices[offset++] = index;
  347. indices[offset++] = vertexIndex + 1;
  348. previousIndex = index;
  349. ++vertexIndex;
  350. }
  351. return offset;
  352. }
  353. /**
  354. * Specifies the quality of terrain created from heightmaps. A value of 1.0 will
  355. * ensure that adjacent heightmap vertices are separated by no more than
  356. * {@link Globe.maximumScreenSpaceError} screen pixels and will probably go very slowly.
  357. * A value of 0.5 will cut the estimated level zero geometric error in half, allowing twice the
  358. * screen pixels between adjacent heightmap vertices and thus rendering more quickly.
  359. * @type {Number}
  360. */
  361. TerrainProvider.heightmapTerrainQuality = 0.25;
  362. /**
  363. * Determines an appropriate geometric error estimate when the geometry comes from a heightmap.
  364. *
  365. * @param {Ellipsoid} ellipsoid The ellipsoid to which the terrain is attached.
  366. * @param {Number} tileImageWidth The width, in pixels, of the heightmap associated with a single tile.
  367. * @param {Number} numberOfTilesAtLevelZero The number of tiles in the horizontal direction at tile level zero.
  368. * @returns {Number} An estimated geometric error.
  369. */
  370. TerrainProvider.getEstimatedLevelZeroGeometricErrorForAHeightmap = function(ellipsoid, tileImageWidth, numberOfTilesAtLevelZero) {
  371. return ellipsoid.maximumRadius * 2 * Math.PI * TerrainProvider.heightmapTerrainQuality / (tileImageWidth * numberOfTilesAtLevelZero);
  372. };
  373. /**
  374. * Requests the geometry for a given tile. This function should not be called before
  375. * {@link TerrainProvider#ready} returns true. The result must include terrain data and
  376. * may optionally include a water mask and an indication of which child tiles are available.
  377. * @function
  378. *
  379. * @param {Number} x The X coordinate of the tile for which to request geometry.
  380. * @param {Number} y The Y coordinate of the tile for which to request geometry.
  381. * @param {Number} level The level of the tile for which to request geometry.
  382. * @param {Request} [request] The request object. Intended for internal use only.
  383. *
  384. * @returns {Promise.<TerrainData>|undefined} A promise for the requested geometry. If this method
  385. * returns undefined instead of a promise, it is an indication that too many requests are already
  386. * pending and the request will be retried later.
  387. */
  388. TerrainProvider.prototype.requestTileGeometry = Check.DeveloperError.throwInstantiationError;
  389. /**
  390. * Gets the maximum geometric error allowed in a tile at a given level. This function should not be
  391. * called before {@link TerrainProvider#ready} returns true.
  392. * @function
  393. *
  394. * @param {Number} level The tile level for which to get the maximum geometric error.
  395. * @returns {Number} The maximum geometric error.
  396. */
  397. TerrainProvider.prototype.getLevelMaximumGeometricError = Check.DeveloperError.throwInstantiationError;
  398. /**
  399. * Determines whether data for a tile is available to be loaded.
  400. * @function
  401. *
  402. * @param {Number} x The X coordinate of the tile for which to request geometry.
  403. * @param {Number} y The Y coordinate of the tile for which to request geometry.
  404. * @param {Number} level The level of the tile for which to request geometry.
  405. * @returns {Boolean} Undefined if not supported by the terrain provider, otherwise true or false.
  406. */
  407. TerrainProvider.prototype.getTileDataAvailable = Check.DeveloperError.throwInstantiationError;
  408. /**
  409. * Makes sure we load availability data for a tile
  410. * @function
  411. *
  412. * @param {Number} x The X coordinate of the tile for which to request geometry.
  413. * @param {Number} y The Y coordinate of the tile for which to request geometry.
  414. * @param {Number} level The level of the tile for which to request geometry.
  415. * @returns {undefined|Promise} Undefined if nothing need to be loaded or a Promise that resolves when all required tiles are loaded
  416. */
  417. TerrainProvider.prototype.loadTileDataAvailability = Check.DeveloperError.throwInstantiationError;
  418. var maxShort = 32767;
  419. var cartesian3Scratch = new Cartographic.Cartesian3();
  420. var scratchMinimum = new Cartographic.Cartesian3();
  421. var scratchMaximum = new Cartographic.Cartesian3();
  422. var cartographicScratch = new Cartographic.Cartographic();
  423. var toPack = new Cartesian2.Cartesian2();
  424. var scratchNormal = new Cartographic.Cartesian3();
  425. var scratchToENU = new BoundingSphere.Matrix4();
  426. var scratchFromENU = new BoundingSphere.Matrix4();
  427. function createVerticesFromQuantizedTerrainMesh(parameters, transferableObjects) {
  428. var quantizedVertices = parameters.quantizedVertices;
  429. var quantizedVertexCount = quantizedVertices.length / 3;
  430. var octEncodedNormals = parameters.octEncodedNormals;
  431. var edgeVertexCount = parameters.westIndices.length + parameters.eastIndices.length +
  432. parameters.southIndices.length + parameters.northIndices.length;
  433. var includeWebMercatorT = parameters.includeWebMercatorT;
  434. var rectangle = Cartesian2.Rectangle.clone(parameters.rectangle);
  435. var west = rectangle.west;
  436. var south = rectangle.south;
  437. var east = rectangle.east;
  438. var north = rectangle.north;
  439. var ellipsoid = Cartesian2.Ellipsoid.clone(parameters.ellipsoid);
  440. var exaggeration = parameters.exaggeration;
  441. var minimumHeight = parameters.minimumHeight * exaggeration;
  442. var maximumHeight = parameters.maximumHeight * exaggeration;
  443. var center = parameters.relativeToCenter;
  444. var fromENU = Transforms.Transforms.eastNorthUpToFixedFrame(center, ellipsoid);
  445. var toENU = BoundingSphere.Matrix4.inverseTransformation(fromENU, new BoundingSphere.Matrix4());
  446. var southMercatorY;
  447. var oneOverMercatorHeight;
  448. if (includeWebMercatorT) {
  449. southMercatorY = WebMercatorProjection.WebMercatorProjection.geodeticLatitudeToMercatorAngle(south);
  450. oneOverMercatorHeight = 1.0 / (WebMercatorProjection.WebMercatorProjection.geodeticLatitudeToMercatorAngle(north) - southMercatorY);
  451. }
  452. var uBuffer = quantizedVertices.subarray(0, quantizedVertexCount);
  453. var vBuffer = quantizedVertices.subarray(quantizedVertexCount, 2 * quantizedVertexCount);
  454. var heightBuffer = quantizedVertices.subarray(quantizedVertexCount * 2, 3 * quantizedVertexCount);
  455. var hasVertexNormals = when.defined(octEncodedNormals);
  456. var uvs = new Array(quantizedVertexCount);
  457. var heights = new Array(quantizedVertexCount);
  458. var positions = new Array(quantizedVertexCount);
  459. var webMercatorTs = includeWebMercatorT ? new Array(quantizedVertexCount) : [];
  460. var minimum = scratchMinimum;
  461. minimum.x = Number.POSITIVE_INFINITY;
  462. minimum.y = Number.POSITIVE_INFINITY;
  463. minimum.z = Number.POSITIVE_INFINITY;
  464. var maximum = scratchMaximum;
  465. maximum.x = Number.NEGATIVE_INFINITY;
  466. maximum.y = Number.NEGATIVE_INFINITY;
  467. maximum.z = Number.NEGATIVE_INFINITY;
  468. var minLongitude = Number.POSITIVE_INFINITY;
  469. var maxLongitude = Number.NEGATIVE_INFINITY;
  470. var minLatitude = Number.POSITIVE_INFINITY;
  471. var maxLatitude = Number.NEGATIVE_INFINITY;
  472. for (var i = 0; i < quantizedVertexCount; ++i) {
  473. var rawU = uBuffer[i];
  474. var rawV = vBuffer[i];
  475. var u = rawU / maxShort;
  476. var v = rawV / maxShort;
  477. var height = _Math.CesiumMath.lerp(minimumHeight, maximumHeight, heightBuffer[i] / maxShort);
  478. cartographicScratch.longitude = _Math.CesiumMath.lerp(west, east, u);
  479. cartographicScratch.latitude = _Math.CesiumMath.lerp(south, north, v);
  480. cartographicScratch.height = height;
  481. minLongitude = Math.min(cartographicScratch.longitude, minLongitude);
  482. maxLongitude = Math.max(cartographicScratch.longitude, maxLongitude);
  483. minLatitude = Math.min(cartographicScratch.latitude, minLatitude);
  484. maxLatitude = Math.max(cartographicScratch.latitude, maxLatitude);
  485. var position = ellipsoid.cartographicToCartesian(cartographicScratch);
  486. uvs[i] = new Cartesian2.Cartesian2(u, v);
  487. heights[i] = height;
  488. positions[i] = position;
  489. if (includeWebMercatorT) {
  490. webMercatorTs[i] = (WebMercatorProjection.WebMercatorProjection.geodeticLatitudeToMercatorAngle(cartographicScratch.latitude) - southMercatorY) * oneOverMercatorHeight;
  491. }
  492. BoundingSphere.Matrix4.multiplyByPoint(toENU, position, cartesian3Scratch);
  493. Cartographic.Cartesian3.minimumByComponent(cartesian3Scratch, minimum, minimum);
  494. Cartographic.Cartesian3.maximumByComponent(cartesian3Scratch, maximum, maximum);
  495. }
  496. var westIndicesSouthToNorth = copyAndSort(parameters.westIndices, function(a, b) {
  497. return uvs[a].y - uvs[b].y;
  498. });
  499. var eastIndicesNorthToSouth = copyAndSort(parameters.eastIndices, function(a, b) {
  500. return uvs[b].y - uvs[a].y;
  501. });
  502. var southIndicesEastToWest = copyAndSort(parameters.southIndices, function(a, b) {
  503. return uvs[b].x - uvs[a].x;
  504. });
  505. var northIndicesWestToEast = copyAndSort(parameters.northIndices, function(a, b) {
  506. return uvs[a].x - uvs[b].x;
  507. });
  508. var orientedBoundingBox;
  509. var boundingSphere;
  510. // Bounding volumes need to be recomputed since the tile payload assumes no exaggeration.
  511. boundingSphere = BoundingSphere.BoundingSphere.fromPoints(positions);
  512. orientedBoundingBox = OrientedBoundingBox.OrientedBoundingBox.fromRectangle(rectangle, minimumHeight, maximumHeight, ellipsoid);
  513. var occludeePointInScaledSpace;
  514. if (exaggeration !== 1.0 || minimumHeight < 0.0) {
  515. // Horizon culling point needs to be recomputed since the tile payload assumes no exaggeration.
  516. var occluder = new TerrainEncoding.EllipsoidalOccluder(ellipsoid);
  517. occludeePointInScaledSpace = occluder.computeHorizonCullingPointPossiblyUnderEllipsoid(center, positions, minimumHeight);
  518. }
  519. var hMin = minimumHeight;
  520. hMin = Math.min(hMin, findMinMaxSkirts(parameters.westIndices, parameters.westSkirtHeight, heights, uvs, rectangle, ellipsoid, toENU, minimum, maximum));
  521. hMin = Math.min(hMin, findMinMaxSkirts(parameters.southIndices, parameters.southSkirtHeight, heights, uvs, rectangle, ellipsoid, toENU, minimum, maximum));
  522. hMin = Math.min(hMin, findMinMaxSkirts(parameters.eastIndices, parameters.eastSkirtHeight, heights, uvs, rectangle, ellipsoid, toENU, minimum, maximum));
  523. hMin = Math.min(hMin, findMinMaxSkirts(parameters.northIndices, parameters.northSkirtHeight, heights, uvs, rectangle, ellipsoid, toENU, minimum, maximum));
  524. var aaBox = new EllipsoidTangentPlane.AxisAlignedBoundingBox(minimum, maximum, center);
  525. var encoding = new TerrainEncoding.TerrainEncoding(aaBox, hMin, maximumHeight, fromENU, hasVertexNormals, includeWebMercatorT);
  526. var vertexStride = encoding.getStride();
  527. var size = quantizedVertexCount * vertexStride + edgeVertexCount * vertexStride;
  528. var vertexBuffer = new Float32Array(size);
  529. var bufferIndex = 0;
  530. for (var j = 0; j < quantizedVertexCount; ++j) {
  531. if (hasVertexNormals) {
  532. var n = j * 2.0;
  533. toPack.x = octEncodedNormals[n];
  534. toPack.y = octEncodedNormals[n + 1];
  535. if (exaggeration !== 1.0) {
  536. var normal = AttributeCompression.AttributeCompression.octDecode(toPack.x, toPack.y, scratchNormal);
  537. var fromENUNormal = Transforms.Transforms.eastNorthUpToFixedFrame(positions[j], ellipsoid, scratchFromENU);
  538. var toENUNormal = BoundingSphere.Matrix4.inverseTransformation(fromENUNormal, scratchToENU);
  539. BoundingSphere.Matrix4.multiplyByPointAsVector(toENUNormal, normal, normal);
  540. normal.z *= exaggeration;
  541. Cartographic.Cartesian3.normalize(normal, normal);
  542. BoundingSphere.Matrix4.multiplyByPointAsVector(fromENUNormal, normal, normal);
  543. Cartographic.Cartesian3.normalize(normal, normal);
  544. AttributeCompression.AttributeCompression.octEncode(normal, toPack);
  545. }
  546. }
  547. bufferIndex = encoding.encode(vertexBuffer, bufferIndex, positions[j], uvs[j], heights[j], toPack, webMercatorTs[j]);
  548. }
  549. var edgeTriangleCount = Math.max(0, (edgeVertexCount - 4) * 2);
  550. var indexBufferLength = parameters.indices.length + edgeTriangleCount * 3;
  551. var indexBuffer = IndexDatatype.IndexDatatype.createTypedArray(quantizedVertexCount + edgeVertexCount, indexBufferLength);
  552. indexBuffer.set(parameters.indices, 0);
  553. var percentage = 0.0001;
  554. var lonOffset = (maxLongitude - minLongitude) * percentage;
  555. var latOffset = (maxLatitude - minLatitude) * percentage;
  556. var westLongitudeOffset = -lonOffset;
  557. var westLatitudeOffset = 0.0;
  558. var eastLongitudeOffset = lonOffset;
  559. var eastLatitudeOffset = 0.0;
  560. var northLongitudeOffset = 0.0;
  561. var northLatitudeOffset = latOffset;
  562. var southLongitudeOffset = 0.0;
  563. var southLatitudeOffset = -latOffset;
  564. // Add skirts.
  565. var vertexBufferIndex = quantizedVertexCount * vertexStride;
  566. addSkirt(vertexBuffer, vertexBufferIndex, westIndicesSouthToNorth, encoding, heights, uvs, octEncodedNormals, ellipsoid, rectangle, parameters.westSkirtHeight, exaggeration, southMercatorY, oneOverMercatorHeight, westLongitudeOffset, westLatitudeOffset);
  567. vertexBufferIndex += parameters.westIndices.length * vertexStride;
  568. addSkirt(vertexBuffer, vertexBufferIndex, southIndicesEastToWest, encoding, heights, uvs, octEncodedNormals, ellipsoid, rectangle, parameters.southSkirtHeight, exaggeration, southMercatorY, oneOverMercatorHeight, southLongitudeOffset, southLatitudeOffset);
  569. vertexBufferIndex += parameters.southIndices.length * vertexStride;
  570. addSkirt(vertexBuffer, vertexBufferIndex, eastIndicesNorthToSouth, encoding, heights, uvs, octEncodedNormals, ellipsoid, rectangle, parameters.eastSkirtHeight, exaggeration, southMercatorY, oneOverMercatorHeight, eastLongitudeOffset, eastLatitudeOffset);
  571. vertexBufferIndex += parameters.eastIndices.length * vertexStride;
  572. addSkirt(vertexBuffer, vertexBufferIndex, northIndicesWestToEast, encoding, heights, uvs, octEncodedNormals, ellipsoid, rectangle, parameters.northSkirtHeight, exaggeration, southMercatorY, oneOverMercatorHeight, northLongitudeOffset, northLatitudeOffset);
  573. var edgeMap = createEdgeMap(parameters.indices, uBuffer, vBuffer, parameters.level);
  574. TerrainProvider.addSkirtIndices(westIndicesSouthToNorth, southIndicesEastToWest, eastIndicesNorthToSouth, northIndicesWestToEast, quantizedVertexCount, indexBuffer, parameters.indices.length, edgeMap);
  575. transferableObjects.push(vertexBuffer.buffer, indexBuffer.buffer);
  576. return {
  577. vertices : vertexBuffer.buffer,
  578. indices : indexBuffer.buffer,
  579. westIndicesSouthToNorth : westIndicesSouthToNorth,
  580. southIndicesEastToWest : southIndicesEastToWest,
  581. eastIndicesNorthToSouth : eastIndicesNorthToSouth,
  582. northIndicesWestToEast : northIndicesWestToEast,
  583. vertexStride : vertexStride,
  584. center : center,
  585. minimumHeight : minimumHeight,
  586. maximumHeight : maximumHeight,
  587. boundingSphere : boundingSphere,
  588. orientedBoundingBox : orientedBoundingBox,
  589. occludeePointInScaledSpace : occludeePointInScaledSpace,
  590. encoding : encoding,
  591. indexCountWithoutSkirts : parameters.indices.length
  592. };
  593. }
  594. function createEdgeMap(indices, uBuffer, vBuffer, level) {
  595. if(level < 12){
  596. return undefined;
  597. }
  598. var edgeMap = {};
  599. var len = indices.length / 3;
  600. for(var i = 0;i < len;i += 3){
  601. var i0 = indices[i];
  602. var i1 = indices[i + 1];
  603. var i2 = indices[i + 2];
  604. if( (uBuffer[i0] === maxShort && uBuffer[i1] === maxShort) ||
  605. (uBuffer[i0] === 0 && uBuffer[i1] === 0) ||
  606. (vBuffer[i0] === maxShort && vBuffer[i1] === maxShort) ||
  607. (vBuffer[i0] === 0 && vBuffer[i1] === 0) ){
  608. edgeMap[i0 + '_' + i1] = 1;
  609. edgeMap[i1 + '_' + i0] = 1;
  610. }
  611. if( (uBuffer[i1] === maxShort && uBuffer[i2] === maxShort) ||
  612. (uBuffer[i1] === 0 && uBuffer[i2] === 0) ||
  613. (vBuffer[i1] === maxShort && vBuffer[i2] === maxShort) ||
  614. (vBuffer[i1] === 0 && vBuffer[i2] === 0) ){
  615. edgeMap[i1 + '_' + i2] = 1;
  616. edgeMap[i2 + '_' + i1] = 1;
  617. }
  618. if( (uBuffer[i2] === maxShort && uBuffer[i0] === maxShort) ||
  619. (uBuffer[i2] === 0 && uBuffer[i0] === 0) ||
  620. (vBuffer[i2] === maxShort && vBuffer[i0] === maxShort) ||
  621. (vBuffer[i2] === 0 && vBuffer[i0] === 0) ){
  622. edgeMap[i2 + '_' + i0] = 1;
  623. edgeMap[i0 + '_' + i2] = 1;
  624. }
  625. }
  626. return edgeMap;
  627. }
  628. function findMinMaxSkirts(edgeIndices, edgeHeight, heights, uvs, rectangle, ellipsoid, toENU, minimum, maximum) {
  629. var hMin = Number.POSITIVE_INFINITY;
  630. var north = rectangle.north;
  631. var south = rectangle.south;
  632. var east = rectangle.east;
  633. var west = rectangle.west;
  634. if (east < west) {
  635. east += _Math.CesiumMath.TWO_PI;
  636. }
  637. var length = edgeIndices.length;
  638. for (var i = 0; i < length; ++i) {
  639. var index = edgeIndices[i];
  640. var h = heights[index];
  641. var uv = uvs[index];
  642. cartographicScratch.longitude = _Math.CesiumMath.lerp(west, east, uv.x);
  643. cartographicScratch.latitude = _Math.CesiumMath.lerp(south, north, uv.y);
  644. cartographicScratch.height = h - edgeHeight;
  645. var position = ellipsoid.cartographicToCartesian(cartographicScratch, cartesian3Scratch);
  646. BoundingSphere.Matrix4.multiplyByPoint(toENU, position, position);
  647. Cartographic.Cartesian3.minimumByComponent(position, minimum, minimum);
  648. Cartographic.Cartesian3.maximumByComponent(position, maximum, maximum);
  649. hMin = Math.min(hMin, cartographicScratch.height);
  650. }
  651. return hMin;
  652. }
  653. function addSkirt(vertexBuffer, vertexBufferIndex, edgeVertices, encoding, heights, uvs, octEncodedNormals, ellipsoid, rectangle, skirtLength, exaggeration, southMercatorY, oneOverMercatorHeight, longitudeOffset, latitudeOffset) {
  654. var hasVertexNormals = when.defined(octEncodedNormals);
  655. var north = rectangle.north;
  656. var south = rectangle.south;
  657. var east = rectangle.east;
  658. var west = rectangle.west;
  659. if (east < west) {
  660. east += _Math.CesiumMath.TWO_PI;
  661. }
  662. var length = edgeVertices.length;
  663. for (var i = 0; i < length; ++i) {
  664. var index = edgeVertices[i];
  665. var h = heights[index];
  666. var uv = uvs[index];
  667. cartographicScratch.longitude = _Math.CesiumMath.lerp(west, east, uv.x) + longitudeOffset;
  668. cartographicScratch.latitude = _Math.CesiumMath.lerp(south, north, uv.y) + latitudeOffset;
  669. cartographicScratch.height = h - skirtLength;
  670. var position = ellipsoid.cartographicToCartesian(cartographicScratch, cartesian3Scratch);
  671. if (hasVertexNormals) {
  672. var n = index * 2.0;
  673. toPack.x = octEncodedNormals[n];
  674. toPack.y = octEncodedNormals[n + 1];
  675. if (exaggeration !== 1.0) {
  676. var normal = AttributeCompression.AttributeCompression.octDecode(toPack.x, toPack.y, scratchNormal);
  677. var fromENUNormal = Transforms.Transforms.eastNorthUpToFixedFrame(cartesian3Scratch, ellipsoid, scratchFromENU);
  678. var toENUNormal = BoundingSphere.Matrix4.inverseTransformation(fromENUNormal, scratchToENU);
  679. BoundingSphere.Matrix4.multiplyByPointAsVector(toENUNormal, normal, normal);
  680. normal.z *= exaggeration;
  681. Cartographic.Cartesian3.normalize(normal, normal);
  682. BoundingSphere.Matrix4.multiplyByPointAsVector(fromENUNormal, normal, normal);
  683. Cartographic.Cartesian3.normalize(normal, normal);
  684. AttributeCompression.AttributeCompression.octEncode(normal, toPack);
  685. }
  686. }
  687. var webMercatorT;
  688. if (encoding.hasWebMercatorT) {
  689. webMercatorT = (WebMercatorProjection.WebMercatorProjection.geodeticLatitudeToMercatorAngle(cartographicScratch.latitude) - southMercatorY) * oneOverMercatorHeight;
  690. }
  691. vertexBufferIndex = encoding.encode(vertexBuffer, vertexBufferIndex, position, uv, cartographicScratch.height, toPack, webMercatorT);
  692. }
  693. }
  694. function copyAndSort(typedArray, comparator) {
  695. var copy;
  696. if (typeof typedArray.slice === 'function') {
  697. copy = typedArray.slice();
  698. if (typeof copy.sort !== 'function') {
  699. // Sliced typed array isn't sortable, so we can't use it.
  700. copy = undefined;
  701. }
  702. }
  703. if (!when.defined(copy)) {
  704. copy = Array.prototype.slice.call(typedArray);
  705. }
  706. copy.sort(comparator);
  707. return copy;
  708. }
  709. var createVerticesFromQuantizedTerrainMesh$1 = createTaskProcessorWorker(createVerticesFromQuantizedTerrainMesh);
  710. return createVerticesFromQuantizedTerrainMesh$1;
  711. });