createVerticesFromHeightmap.js 107 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710
  1. define(['./Matrix3-41c58dde', './AxisAlignedBoundingBox-31fadcf0', './Transforms-bc45e707', './Matrix2-e1298525', './defaultValue-fe22d8c0', './Check-6ede7e26', './TerrainEncoding-51b8b33b', './Math-0a2ac845', './OrientedBoundingBox-2dd47921', './WebMercatorProjection-13ed1a6e', './RuntimeError-ef395448', './createTaskProcessorWorker', './combine-d9581036', './AttributeCompression-f9f6c717', './ComponentDatatype-cf1fa08e', './WebGLConstants-0b1ce7ba', './EllipsoidTangentPlane-46d4d9c2', './IntersectionTests-88c49b2e', './Plane-4c3d403b'], (function (Matrix3, AxisAlignedBoundingBox, Transforms, Matrix2, defaultValue, Check, TerrainEncoding, Math$1, OrientedBoundingBox, WebMercatorProjection, RuntimeError, createTaskProcessorWorker, combine, AttributeCompression, ComponentDatatype, WebGLConstants, EllipsoidTangentPlane, IntersectionTests, Plane) { 'use strict';
  2. /**
  3. * The encoding that is used for a heightmap
  4. *
  5. * @enum {number}
  6. */
  7. const HeightmapEncoding = {
  8. /**
  9. * No encoding
  10. *
  11. * @type {number}
  12. * @constant
  13. */
  14. NONE: 0,
  15. /**
  16. * LERC encoding
  17. *
  18. * @type {number}
  19. * @constant
  20. *
  21. * @see {@link https://github.com/Esri/lerc|The LERC specification}
  22. */
  23. LERC: 1,
  24. };
  25. var HeightmapEncoding$1 = Object.freeze(HeightmapEncoding);
  26. /**
  27. * Contains functions to create a mesh from a heightmap image.
  28. *
  29. * @namespace HeightmapTessellator
  30. *
  31. * @private
  32. */
  33. const HeightmapTessellator = {};
  34. /**
  35. * The default structure of a heightmap, as given to {@link HeightmapTessellator.computeVertices}.
  36. *
  37. * @constant
  38. */
  39. HeightmapTessellator.DEFAULT_STRUCTURE = Object.freeze({
  40. heightScale: 1.0,
  41. heightOffset: 0.0,
  42. elementsPerHeight: 1,
  43. stride: 1,
  44. elementMultiplier: 256.0,
  45. isBigEndian: false,
  46. });
  47. const cartesian3Scratch = new Matrix3.Cartesian3();
  48. const matrix4Scratch = new Matrix2.Matrix4();
  49. const minimumScratch = new Matrix3.Cartesian3();
  50. const maximumScratch = new Matrix3.Cartesian3();
  51. /**
  52. * Fills an array of vertices from a heightmap image.
  53. *
  54. * @param {object} options Object with the following properties:
  55. * @param {Int8Array|Uint8Array|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array|Float64Array} options.heightmap The heightmap to tessellate.
  56. * @param {number} options.width The width of the heightmap, in height samples.
  57. * @param {number} options.height The height of the heightmap, in height samples.
  58. * @param {number} options.skirtHeight The height of skirts to drape at the edges of the heightmap.
  59. * @param {Rectangle} options.nativeRectangle A rectangle in the native coordinates of the heightmap's projection. For
  60. * a heightmap with a geographic projection, this is degrees. For the web mercator
  61. * projection, this is meters.
  62. * @param {number} [options.exaggeration=1.0] The scale used to exaggerate the terrain.
  63. * @param {number} [options.exaggerationRelativeHeight=0.0] The height from which terrain is exaggerated.
  64. * @param {Rectangle} [options.rectangle] The rectangle covered by the heightmap, in geodetic coordinates with north, south, east and
  65. * west properties in radians. Either rectangle or nativeRectangle must be provided. If both
  66. * are provided, they're assumed to be consistent.
  67. * @param {boolean} [options.isGeographic=true] True if the heightmap uses a {@link GeographicProjection}, or false if it uses
  68. * a {@link WebMercatorProjection}.
  69. * @param {Cartesian3} [options.relativeToCenter=Cartesian3.ZERO] The positions will be computed as <code>Cartesian3.subtract(worldPosition, relativeToCenter)</code>.
  70. * @param {Ellipsoid} [options.ellipsoid=Ellipsoid.WGS84] The ellipsoid to which the heightmap applies.
  71. * @param {object} [options.structure] An object describing the structure of the height data.
  72. * @param {number} [options.structure.heightScale=1.0] The factor by which to multiply height samples in order to obtain
  73. * the height above the heightOffset, in meters. The heightOffset is added to the resulting
  74. * height after multiplying by the scale.
  75. * @param {number} [options.structure.heightOffset=0.0] The offset to add to the scaled height to obtain the final
  76. * height in meters. The offset is added after the height sample is multiplied by the
  77. * heightScale.
  78. * @param {number} [options.structure.elementsPerHeight=1] The number of elements in the buffer that make up a single height
  79. * sample. This is usually 1, indicating that each element is a separate height sample. If
  80. * it is greater than 1, that number of elements together form the height sample, which is
  81. * computed according to the structure.elementMultiplier and structure.isBigEndian properties.
  82. * @param {number} [options.structure.stride=1] The number of elements to skip to get from the first element of
  83. * one height to the first element of the next height.
  84. * @param {number} [options.structure.elementMultiplier=256.0] The multiplier used to compute the height value when the
  85. * stride property is greater than 1. For example, if the stride is 4 and the strideMultiplier
  86. * is 256, the height is computed as follows:
  87. * `height = buffer[index] + buffer[index + 1] * 256 + buffer[index + 2] * 256 * 256 + buffer[index + 3] * 256 * 256 * 256`
  88. * This is assuming that the isBigEndian property is false. If it is true, the order of the
  89. * elements is reversed.
  90. * @param {number} [options.structure.lowestEncodedHeight] The lowest value that can be stored in the height buffer. Any heights that are lower
  91. * than this value after encoding with the `heightScale` and `heightOffset` are clamped to this value. For example, if the height
  92. * buffer is a `Uint16Array`, this value should be 0 because a `Uint16Array` cannot store negative numbers. If this parameter is
  93. * not specified, no minimum value is enforced.
  94. * @param {number} [options.structure.highestEncodedHeight] The highest value that can be stored in the height buffer. Any heights that are higher
  95. * than this value after encoding with the `heightScale` and `heightOffset` are clamped to this value. For example, if the height
  96. * buffer is a `Uint16Array`, this value should be `256 * 256 - 1` or 65535 because a `Uint16Array` cannot store numbers larger
  97. * than 65535. If this parameter is not specified, no maximum value is enforced.
  98. * @param {boolean} [options.structure.isBigEndian=false] Indicates endianness of the elements in the buffer when the
  99. * stride property is greater than 1. If this property is false, the first element is the
  100. * low-order element. If it is true, the first element is the high-order element.
  101. *
  102. * @example
  103. * const width = 5;
  104. * const height = 5;
  105. * const statistics = Cesium.HeightmapTessellator.computeVertices({
  106. * heightmap : [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0],
  107. * width : width,
  108. * height : height,
  109. * skirtHeight : 0.0,
  110. * nativeRectangle : {
  111. * west : 10.0,
  112. * east : 20.0,
  113. * south : 30.0,
  114. * north : 40.0
  115. * }
  116. * });
  117. *
  118. * const encoding = statistics.encoding;
  119. * const position = encoding.decodePosition(statistics.vertices, index);
  120. */
  121. HeightmapTessellator.computeVertices = function (options) {
  122. //>>includeStart('debug', pragmas.debug);
  123. if (!defaultValue.defined(options) || !defaultValue.defined(options.heightmap)) {
  124. throw new Check.DeveloperError("options.heightmap is required.");
  125. }
  126. if (!defaultValue.defined(options.width) || !defaultValue.defined(options.height)) {
  127. throw new Check.DeveloperError("options.width and options.height are required.");
  128. }
  129. if (!defaultValue.defined(options.nativeRectangle)) {
  130. throw new Check.DeveloperError("options.nativeRectangle is required.");
  131. }
  132. if (!defaultValue.defined(options.skirtHeight)) {
  133. throw new Check.DeveloperError("options.skirtHeight is required.");
  134. }
  135. //>>includeEnd('debug');
  136. // This function tends to be a performance hotspot for terrain rendering,
  137. // so it employs a lot of inlining and unrolling as an optimization.
  138. // In particular, the functionality of Ellipsoid.cartographicToCartesian
  139. // is inlined.
  140. const cos = Math.cos;
  141. const sin = Math.sin;
  142. const sqrt = Math.sqrt;
  143. const atan = Math.atan;
  144. const exp = Math.exp;
  145. const piOverTwo = Math$1.CesiumMath.PI_OVER_TWO;
  146. const toRadians = Math$1.CesiumMath.toRadians;
  147. const heightmap = options.heightmap;
  148. const width = options.width;
  149. const height = options.height;
  150. const skirtHeight = options.skirtHeight;
  151. const hasSkirts = skirtHeight > 0.0;
  152. const isGeographic = defaultValue.defaultValue(options.isGeographic, true);
  153. const ellipsoid = defaultValue.defaultValue(options.ellipsoid, Matrix3.Ellipsoid.WGS84);
  154. const oneOverGlobeSemimajorAxis = 1.0 / ellipsoid.maximumRadius;
  155. const nativeRectangle = Matrix2.Rectangle.clone(options.nativeRectangle);
  156. const rectangle = Matrix2.Rectangle.clone(options.rectangle);
  157. let geographicWest;
  158. let geographicSouth;
  159. let geographicEast;
  160. let geographicNorth;
  161. if (!defaultValue.defined(rectangle)) {
  162. if (isGeographic) {
  163. geographicWest = toRadians(nativeRectangle.west);
  164. geographicSouth = toRadians(nativeRectangle.south);
  165. geographicEast = toRadians(nativeRectangle.east);
  166. geographicNorth = toRadians(nativeRectangle.north);
  167. } else {
  168. geographicWest = nativeRectangle.west * oneOverGlobeSemimajorAxis;
  169. geographicSouth =
  170. piOverTwo -
  171. 2.0 * atan(exp(-nativeRectangle.south * oneOverGlobeSemimajorAxis));
  172. geographicEast = nativeRectangle.east * oneOverGlobeSemimajorAxis;
  173. geographicNorth =
  174. piOverTwo -
  175. 2.0 * atan(exp(-nativeRectangle.north * oneOverGlobeSemimajorAxis));
  176. }
  177. } else {
  178. geographicWest = rectangle.west;
  179. geographicSouth = rectangle.south;
  180. geographicEast = rectangle.east;
  181. geographicNorth = rectangle.north;
  182. }
  183. let relativeToCenter = options.relativeToCenter;
  184. const hasRelativeToCenter = defaultValue.defined(relativeToCenter);
  185. relativeToCenter = hasRelativeToCenter ? relativeToCenter : Matrix3.Cartesian3.ZERO;
  186. const includeWebMercatorT = defaultValue.defaultValue(options.includeWebMercatorT, false);
  187. const exaggeration = defaultValue.defaultValue(options.exaggeration, 1.0);
  188. const exaggerationRelativeHeight = defaultValue.defaultValue(
  189. options.exaggerationRelativeHeight,
  190. 0.0
  191. );
  192. const hasExaggeration = exaggeration !== 1.0;
  193. const includeGeodeticSurfaceNormals = hasExaggeration;
  194. const structure = defaultValue.defaultValue(
  195. options.structure,
  196. HeightmapTessellator.DEFAULT_STRUCTURE
  197. );
  198. const heightScale = defaultValue.defaultValue(
  199. structure.heightScale,
  200. HeightmapTessellator.DEFAULT_STRUCTURE.heightScale
  201. );
  202. const heightOffset = defaultValue.defaultValue(
  203. structure.heightOffset,
  204. HeightmapTessellator.DEFAULT_STRUCTURE.heightOffset
  205. );
  206. const elementsPerHeight = defaultValue.defaultValue(
  207. structure.elementsPerHeight,
  208. HeightmapTessellator.DEFAULT_STRUCTURE.elementsPerHeight
  209. );
  210. const stride = defaultValue.defaultValue(
  211. structure.stride,
  212. HeightmapTessellator.DEFAULT_STRUCTURE.stride
  213. );
  214. const elementMultiplier = defaultValue.defaultValue(
  215. structure.elementMultiplier,
  216. HeightmapTessellator.DEFAULT_STRUCTURE.elementMultiplier
  217. );
  218. const isBigEndian = defaultValue.defaultValue(
  219. structure.isBigEndian,
  220. HeightmapTessellator.DEFAULT_STRUCTURE.isBigEndian
  221. );
  222. let rectangleWidth = Matrix2.Rectangle.computeWidth(nativeRectangle);
  223. let rectangleHeight = Matrix2.Rectangle.computeHeight(nativeRectangle);
  224. const granularityX = rectangleWidth / (width - 1);
  225. const granularityY = rectangleHeight / (height - 1);
  226. if (!isGeographic) {
  227. rectangleWidth *= oneOverGlobeSemimajorAxis;
  228. rectangleHeight *= oneOverGlobeSemimajorAxis;
  229. }
  230. const radiiSquared = ellipsoid.radiiSquared;
  231. const radiiSquaredX = radiiSquared.x;
  232. const radiiSquaredY = radiiSquared.y;
  233. const radiiSquaredZ = radiiSquared.z;
  234. let minimumHeight = 65536.0;
  235. let maximumHeight = -65536.0;
  236. const fromENU = Transforms.Transforms.eastNorthUpToFixedFrame(
  237. relativeToCenter,
  238. ellipsoid
  239. );
  240. const toENU = Matrix2.Matrix4.inverseTransformation(fromENU, matrix4Scratch);
  241. let southMercatorY;
  242. let oneOverMercatorHeight;
  243. if (includeWebMercatorT) {
  244. southMercatorY = WebMercatorProjection.WebMercatorProjection.geodeticLatitudeToMercatorAngle(
  245. geographicSouth
  246. );
  247. oneOverMercatorHeight =
  248. 1.0 /
  249. (WebMercatorProjection.WebMercatorProjection.geodeticLatitudeToMercatorAngle(geographicNorth) -
  250. southMercatorY);
  251. }
  252. const minimum = minimumScratch;
  253. minimum.x = Number.POSITIVE_INFINITY;
  254. minimum.y = Number.POSITIVE_INFINITY;
  255. minimum.z = Number.POSITIVE_INFINITY;
  256. const maximum = maximumScratch;
  257. maximum.x = Number.NEGATIVE_INFINITY;
  258. maximum.y = Number.NEGATIVE_INFINITY;
  259. maximum.z = Number.NEGATIVE_INFINITY;
  260. let hMin = Number.POSITIVE_INFINITY;
  261. const gridVertexCount = width * height;
  262. const edgeVertexCount = skirtHeight > 0.0 ? width * 2 + height * 2 : 0;
  263. const vertexCount = gridVertexCount + edgeVertexCount;
  264. const positions = new Array(vertexCount);
  265. const heights = new Array(vertexCount);
  266. const uvs = new Array(vertexCount);
  267. const webMercatorTs = includeWebMercatorT ? new Array(vertexCount) : [];
  268. const geodeticSurfaceNormals = includeGeodeticSurfaceNormals
  269. ? new Array(vertexCount)
  270. : [];
  271. let startRow = 0;
  272. let endRow = height;
  273. let startCol = 0;
  274. let endCol = width;
  275. if (hasSkirts) {
  276. --startRow;
  277. ++endRow;
  278. --startCol;
  279. ++endCol;
  280. }
  281. const skirtOffsetPercentage = 0.00001;
  282. for (let rowIndex = startRow; rowIndex < endRow; ++rowIndex) {
  283. let row = rowIndex;
  284. if (row < 0) {
  285. row = 0;
  286. }
  287. if (row >= height) {
  288. row = height - 1;
  289. }
  290. let latitude = nativeRectangle.north - granularityY * row;
  291. if (!isGeographic) {
  292. latitude =
  293. piOverTwo - 2.0 * atan(exp(-latitude * oneOverGlobeSemimajorAxis));
  294. } else {
  295. latitude = toRadians(latitude);
  296. }
  297. let v = (latitude - geographicSouth) / (geographicNorth - geographicSouth);
  298. v = Math$1.CesiumMath.clamp(v, 0.0, 1.0);
  299. const isNorthEdge = rowIndex === startRow;
  300. const isSouthEdge = rowIndex === endRow - 1;
  301. if (skirtHeight > 0.0) {
  302. if (isNorthEdge) {
  303. latitude += skirtOffsetPercentage * rectangleHeight;
  304. } else if (isSouthEdge) {
  305. latitude -= skirtOffsetPercentage * rectangleHeight;
  306. }
  307. }
  308. const cosLatitude = cos(latitude);
  309. const nZ = sin(latitude);
  310. const kZ = radiiSquaredZ * nZ;
  311. let webMercatorT;
  312. if (includeWebMercatorT) {
  313. webMercatorT =
  314. (WebMercatorProjection.WebMercatorProjection.geodeticLatitudeToMercatorAngle(latitude) -
  315. southMercatorY) *
  316. oneOverMercatorHeight;
  317. }
  318. for (let colIndex = startCol; colIndex < endCol; ++colIndex) {
  319. let col = colIndex;
  320. if (col < 0) {
  321. col = 0;
  322. }
  323. if (col >= width) {
  324. col = width - 1;
  325. }
  326. const terrainOffset = row * (width * stride) + col * stride;
  327. let heightSample;
  328. if (elementsPerHeight === 1) {
  329. heightSample = heightmap[terrainOffset];
  330. } else {
  331. heightSample = 0;
  332. let elementOffset;
  333. if (isBigEndian) {
  334. for (
  335. elementOffset = 0;
  336. elementOffset < elementsPerHeight;
  337. ++elementOffset
  338. ) {
  339. heightSample =
  340. heightSample * elementMultiplier +
  341. heightmap[terrainOffset + elementOffset];
  342. }
  343. } else {
  344. for (
  345. elementOffset = elementsPerHeight - 1;
  346. elementOffset >= 0;
  347. --elementOffset
  348. ) {
  349. heightSample =
  350. heightSample * elementMultiplier +
  351. heightmap[terrainOffset + elementOffset];
  352. }
  353. }
  354. }
  355. heightSample = heightSample * heightScale + heightOffset;
  356. maximumHeight = Math.max(maximumHeight, heightSample);
  357. minimumHeight = Math.min(minimumHeight, heightSample);
  358. let longitude = nativeRectangle.west + granularityX * col;
  359. if (!isGeographic) {
  360. longitude = longitude * oneOverGlobeSemimajorAxis;
  361. } else {
  362. longitude = toRadians(longitude);
  363. }
  364. let u = (longitude - geographicWest) / (geographicEast - geographicWest);
  365. u = Math$1.CesiumMath.clamp(u, 0.0, 1.0);
  366. let index = row * width + col;
  367. if (skirtHeight > 0.0) {
  368. const isWestEdge = colIndex === startCol;
  369. const isEastEdge = colIndex === endCol - 1;
  370. const isEdge = isNorthEdge || isSouthEdge || isWestEdge || isEastEdge;
  371. const isCorner =
  372. (isNorthEdge || isSouthEdge) && (isWestEdge || isEastEdge);
  373. if (isCorner) {
  374. // Don't generate skirts on the corners.
  375. continue;
  376. } else if (isEdge) {
  377. heightSample -= skirtHeight;
  378. if (isWestEdge) {
  379. // The outer loop iterates north to south but the indices are ordered south to north, hence the index flip below
  380. index = gridVertexCount + (height - row - 1);
  381. longitude -= skirtOffsetPercentage * rectangleWidth;
  382. } else if (isSouthEdge) {
  383. // Add after west indices. South indices are ordered east to west.
  384. index = gridVertexCount + height + (width - col - 1);
  385. } else if (isEastEdge) {
  386. // Add after west and south indices. East indices are ordered north to south. The index is flipped like above.
  387. index = gridVertexCount + height + width + row;
  388. longitude += skirtOffsetPercentage * rectangleWidth;
  389. } else if (isNorthEdge) {
  390. // Add after west, south, and east indices. North indices are ordered west to east.
  391. index = gridVertexCount + height + width + height + col;
  392. }
  393. }
  394. }
  395. const nX = cosLatitude * cos(longitude);
  396. const nY = cosLatitude * sin(longitude);
  397. const kX = radiiSquaredX * nX;
  398. const kY = radiiSquaredY * nY;
  399. const gamma = sqrt(kX * nX + kY * nY + kZ * nZ);
  400. const oneOverGamma = 1.0 / gamma;
  401. const rSurfaceX = kX * oneOverGamma;
  402. const rSurfaceY = kY * oneOverGamma;
  403. const rSurfaceZ = kZ * oneOverGamma;
  404. const position = new Matrix3.Cartesian3();
  405. position.x = rSurfaceX + nX * heightSample;
  406. position.y = rSurfaceY + nY * heightSample;
  407. position.z = rSurfaceZ + nZ * heightSample;
  408. Matrix2.Matrix4.multiplyByPoint(toENU, position, cartesian3Scratch);
  409. Matrix3.Cartesian3.minimumByComponent(cartesian3Scratch, minimum, minimum);
  410. Matrix3.Cartesian3.maximumByComponent(cartesian3Scratch, maximum, maximum);
  411. hMin = Math.min(hMin, heightSample);
  412. positions[index] = position;
  413. uvs[index] = new Matrix2.Cartesian2(u, v);
  414. heights[index] = heightSample;
  415. if (includeWebMercatorT) {
  416. webMercatorTs[index] = webMercatorT;
  417. }
  418. if (includeGeodeticSurfaceNormals) {
  419. geodeticSurfaceNormals[index] = ellipsoid.geodeticSurfaceNormal(
  420. position
  421. );
  422. }
  423. }
  424. }
  425. const boundingSphere3D = Transforms.BoundingSphere.fromPoints(positions);
  426. let orientedBoundingBox;
  427. if (defaultValue.defined(rectangle)) {
  428. orientedBoundingBox = OrientedBoundingBox.OrientedBoundingBox.fromRectangle(
  429. rectangle,
  430. minimumHeight,
  431. maximumHeight,
  432. ellipsoid
  433. );
  434. }
  435. let occludeePointInScaledSpace;
  436. if (hasRelativeToCenter) {
  437. const occluder = new TerrainEncoding.EllipsoidalOccluder(ellipsoid);
  438. occludeePointInScaledSpace = occluder.computeHorizonCullingPointPossiblyUnderEllipsoid(
  439. relativeToCenter,
  440. positions,
  441. minimumHeight
  442. );
  443. }
  444. const aaBox = new AxisAlignedBoundingBox.AxisAlignedBoundingBox(minimum, maximum, relativeToCenter);
  445. const encoding = new TerrainEncoding.TerrainEncoding(
  446. relativeToCenter,
  447. aaBox,
  448. hMin,
  449. maximumHeight,
  450. fromENU,
  451. false,
  452. includeWebMercatorT,
  453. includeGeodeticSurfaceNormals,
  454. exaggeration,
  455. exaggerationRelativeHeight
  456. );
  457. const vertices = new Float32Array(vertexCount * encoding.stride);
  458. let bufferIndex = 0;
  459. for (let j = 0; j < vertexCount; ++j) {
  460. bufferIndex = encoding.encode(
  461. vertices,
  462. bufferIndex,
  463. positions[j],
  464. uvs[j],
  465. heights[j],
  466. undefined,
  467. webMercatorTs[j],
  468. geodeticSurfaceNormals[j]
  469. );
  470. }
  471. return {
  472. vertices: vertices,
  473. maximumHeight: maximumHeight,
  474. minimumHeight: minimumHeight,
  475. encoding: encoding,
  476. boundingSphere3D: boundingSphere3D,
  477. orientedBoundingBox: orientedBoundingBox,
  478. occludeePointInScaledSpace: occludeePointInScaledSpace,
  479. };
  480. };
  481. var HeightmapTessellator$1 = HeightmapTessellator;
  482. var LercDecode = {exports: {}};
  483. /* jshint forin: false, bitwise: false */
  484. (function (module) {
  485. /*
  486. Copyright 2015-2018 Esri
  487. Licensed under the Apache License, Version 2.0 (the "License");
  488. you may not use this file except in compliance with the License.
  489. You may obtain a copy of the License at
  490. http://www.apache.org/licenses/LICENSE-2.0
  491. Unless required by applicable law or agreed to in writing, software
  492. distributed under the License is distributed on an "AS IS" BASIS,
  493. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  494. See the License for the specific language governing permissions and
  495. limitations under the License.
  496. A copy of the license and additional notices are located with the
  497. source distribution at:
  498. http://github.com/Esri/lerc/
  499. Contributors: Johannes Schmid, (LERC v1)
  500. Chayanika Khatua, (LERC v1)
  501. Wenxue Ju (LERC v1, v2.x)
  502. */
  503. /* Copyright 2015-2018 Esri. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 @preserve */
  504. /**
  505. * a module for decoding LERC blobs
  506. * @module Lerc
  507. */
  508. (function() {
  509. //the original LercDecode for Version 1
  510. var LercDecode = (function() {
  511. // WARNING: This decoder version can only read old version 1 Lerc blobs. Use with caution.
  512. // Note: currently, this module only has an implementation for decoding LERC data, not encoding. The name of
  513. // the class was chosen to be future proof.
  514. var CntZImage = {};
  515. CntZImage.defaultNoDataValue = -3.4027999387901484e+38; // smallest Float32 value
  516. /**
  517. * Decode a LERC byte stream and return an object containing the pixel data and some required and optional
  518. * information about it, such as the image's width and height.
  519. *
  520. * @param {ArrayBuffer} input The LERC input byte stream
  521. * @param {object} [options] Decoding options, containing any of the following properties:
  522. * @config {number} [inputOffset = 0]
  523. * Skip the first inputOffset bytes of the input byte stream. A valid LERC file is expected at that position.
  524. * @config {Uint8Array} [encodedMask = null]
  525. * If specified, the decoder will not read mask information from the input and use the specified encoded
  526. * mask data instead. Mask header/data must not be present in the LERC byte stream in this case.
  527. * @config {number} [noDataValue = LercCode.defaultNoDataValue]
  528. * Pixel value to use for masked pixels.
  529. * @config {ArrayBufferView|Array} [pixelType = Float32Array]
  530. * The desired type of the pixelData array in the return value. Note that it is the caller's responsibility to
  531. * provide an appropriate noDataValue if the default pixelType is overridden.
  532. * @config {boolean} [returnMask = false]
  533. * If true, the return value will contain a maskData property of type Uint8Array which has one element per
  534. * pixel, the value of which is 1 or 0 depending on whether that pixel's data is present or masked. If the
  535. * input LERC data does not contain a mask, maskData will not be returned.
  536. * @config {boolean} [returnEncodedMask = false]
  537. * If true, the return value will contain a encodedMaskData property, which can be passed into encode() as
  538. * encodedMask.
  539. * @config {boolean} [returnFileInfo = false]
  540. * If true, the return value will have a fileInfo property that contains metadata obtained from the
  541. * LERC headers and the decoding process.
  542. * @config {boolean} [computeUsedBitDepths = false]
  543. * If true, the fileInfo property in the return value will contain the set of all block bit depths
  544. * encountered during decoding. Will only have an effect if returnFileInfo option is true.
  545. * @returns {{width, height, pixelData, minValue, maxValue, noDataValue, maskData, encodedMaskData, fileInfo}}
  546. */
  547. CntZImage.decode = function(input, options) {
  548. options = options || {};
  549. var skipMask = options.encodedMaskData || (options.encodedMaskData === null);
  550. var parsedData = parse(input, options.inputOffset || 0, skipMask);
  551. var noDataValue = (options.noDataValue !== null) ? options.noDataValue : CntZImage.defaultNoDataValue;
  552. var uncompressedData = uncompressPixelValues(parsedData, options.pixelType || Float32Array,
  553. options.encodedMaskData, noDataValue, options.returnMask);
  554. var result = {
  555. width: parsedData.width,
  556. height: parsedData.height,
  557. pixelData: uncompressedData.resultPixels,
  558. minValue: uncompressedData.minValue,
  559. maxValue: parsedData.pixels.maxValue,
  560. noDataValue: noDataValue
  561. };
  562. if (uncompressedData.resultMask) {
  563. result.maskData = uncompressedData.resultMask;
  564. }
  565. if (options.returnEncodedMask && parsedData.mask) {
  566. result.encodedMaskData = parsedData.mask.bitset ? parsedData.mask.bitset : null;
  567. }
  568. if (options.returnFileInfo) {
  569. result.fileInfo = formatFileInfo(parsedData);
  570. if (options.computeUsedBitDepths) {
  571. result.fileInfo.bitDepths = computeUsedBitDepths(parsedData);
  572. }
  573. }
  574. return result;
  575. };
  576. var uncompressPixelValues = function(data, TypedArrayClass, maskBitset, noDataValue, storeDecodedMask) {
  577. var blockIdx = 0;
  578. var numX = data.pixels.numBlocksX;
  579. var numY = data.pixels.numBlocksY;
  580. var blockWidth = Math.floor(data.width / numX);
  581. var blockHeight = Math.floor(data.height / numY);
  582. var scale = 2 * data.maxZError;
  583. var minValue = Number.MAX_VALUE, currentValue;
  584. maskBitset = maskBitset || ((data.mask) ? data.mask.bitset : null);
  585. var resultPixels, resultMask;
  586. resultPixels = new TypedArrayClass(data.width * data.height);
  587. if (storeDecodedMask && maskBitset) {
  588. resultMask = new Uint8Array(data.width * data.height);
  589. }
  590. var blockDataBuffer = new Float32Array(blockWidth * blockHeight);
  591. var xx, yy;
  592. for (var y = 0; y <= numY; y++) {
  593. var thisBlockHeight = (y !== numY) ? blockHeight : (data.height % numY);
  594. if (thisBlockHeight === 0) {
  595. continue;
  596. }
  597. for (var x = 0; x <= numX; x++) {
  598. var thisBlockWidth = (x !== numX) ? blockWidth : (data.width % numX);
  599. if (thisBlockWidth === 0) {
  600. continue;
  601. }
  602. var outPtr = y * data.width * blockHeight + x * blockWidth;
  603. var outStride = data.width - thisBlockWidth;
  604. var block = data.pixels.blocks[blockIdx];
  605. var blockData, blockPtr, constValue;
  606. if (block.encoding < 2) {
  607. // block is either uncompressed or bit-stuffed (encodings 0 and 1)
  608. if (block.encoding === 0) {
  609. // block is uncompressed
  610. blockData = block.rawData;
  611. } else {
  612. // block is bit-stuffed
  613. unstuff(block.stuffedData, block.bitsPerPixel, block.numValidPixels, block.offset, scale, blockDataBuffer, data.pixels.maxValue);
  614. blockData = blockDataBuffer;
  615. }
  616. blockPtr = 0;
  617. }
  618. else if (block.encoding === 2) {
  619. // block is all 0
  620. constValue = 0;
  621. }
  622. else {
  623. // block has constant value (encoding === 3)
  624. constValue = block.offset;
  625. }
  626. var maskByte;
  627. if (maskBitset) {
  628. for (yy = 0; yy < thisBlockHeight; yy++) {
  629. if (outPtr & 7) {
  630. //
  631. maskByte = maskBitset[outPtr >> 3];
  632. maskByte <<= outPtr & 7;
  633. }
  634. for (xx = 0; xx < thisBlockWidth; xx++) {
  635. if (!(outPtr & 7)) {
  636. // read next byte from mask
  637. maskByte = maskBitset[outPtr >> 3];
  638. }
  639. if (maskByte & 128) {
  640. // pixel data present
  641. if (resultMask) {
  642. resultMask[outPtr] = 1;
  643. }
  644. currentValue = (block.encoding < 2) ? blockData[blockPtr++] : constValue;
  645. minValue = minValue > currentValue ? currentValue : minValue;
  646. resultPixels[outPtr++] = currentValue;
  647. } else {
  648. // pixel data not present
  649. if (resultMask) {
  650. resultMask[outPtr] = 0;
  651. }
  652. resultPixels[outPtr++] = noDataValue;
  653. }
  654. maskByte <<= 1;
  655. }
  656. outPtr += outStride;
  657. }
  658. } else {
  659. // mask not present, simply copy block over
  660. if (block.encoding < 2) {
  661. // duplicating this code block for performance reasons
  662. // blockData case:
  663. for (yy = 0; yy < thisBlockHeight; yy++) {
  664. for (xx = 0; xx < thisBlockWidth; xx++) {
  665. currentValue = blockData[blockPtr++];
  666. minValue = minValue > currentValue ? currentValue : minValue;
  667. resultPixels[outPtr++] = currentValue;
  668. }
  669. outPtr += outStride;
  670. }
  671. }
  672. else {
  673. // constValue case:
  674. minValue = minValue > constValue ? constValue : minValue;
  675. for (yy = 0; yy < thisBlockHeight; yy++) {
  676. for (xx = 0; xx < thisBlockWidth; xx++) {
  677. resultPixels[outPtr++] = constValue;
  678. }
  679. outPtr += outStride;
  680. }
  681. }
  682. }
  683. if ((block.encoding === 1) && (blockPtr !== block.numValidPixels)) {
  684. throw "Block and Mask do not match";
  685. }
  686. blockIdx++;
  687. }
  688. }
  689. return {
  690. resultPixels: resultPixels,
  691. resultMask: resultMask,
  692. minValue: minValue
  693. };
  694. };
  695. var formatFileInfo = function(data) {
  696. return {
  697. "fileIdentifierString": data.fileIdentifierString,
  698. "fileVersion": data.fileVersion,
  699. "imageType": data.imageType,
  700. "height": data.height,
  701. "width": data.width,
  702. "maxZError": data.maxZError,
  703. "eofOffset": data.eofOffset,
  704. "mask": data.mask ? {
  705. "numBlocksX": data.mask.numBlocksX,
  706. "numBlocksY": data.mask.numBlocksY,
  707. "numBytes": data.mask.numBytes,
  708. "maxValue": data.mask.maxValue
  709. } : null,
  710. "pixels": {
  711. "numBlocksX": data.pixels.numBlocksX,
  712. "numBlocksY": data.pixels.numBlocksY,
  713. "numBytes": data.pixels.numBytes,
  714. "maxValue": data.pixels.maxValue,
  715. "noDataValue": data.noDataValue
  716. }
  717. };
  718. };
  719. var computeUsedBitDepths = function(data) {
  720. var numBlocks = data.pixels.numBlocksX * data.pixels.numBlocksY;
  721. var bitDepths = {};
  722. for (var i = 0; i < numBlocks; i++) {
  723. var block = data.pixels.blocks[i];
  724. if (block.encoding === 0) {
  725. bitDepths.float32 = true;
  726. } else if (block.encoding === 1) {
  727. bitDepths[block.bitsPerPixel] = true;
  728. } else {
  729. bitDepths[0] = true;
  730. }
  731. }
  732. return Object.keys(bitDepths);
  733. };
  734. var parse = function(input, fp, skipMask) {
  735. var data = {};
  736. // File header
  737. var fileIdView = new Uint8Array(input, fp, 10);
  738. data.fileIdentifierString = String.fromCharCode.apply(null, fileIdView);
  739. if (data.fileIdentifierString.trim() !== "CntZImage") {
  740. throw "Unexpected file identifier string: " + data.fileIdentifierString;
  741. }
  742. fp += 10;
  743. var view = new DataView(input, fp, 24);
  744. data.fileVersion = view.getInt32(0, true);
  745. data.imageType = view.getInt32(4, true);
  746. data.height = view.getUint32(8, true);
  747. data.width = view.getUint32(12, true);
  748. data.maxZError = view.getFloat64(16, true);
  749. fp += 24;
  750. // Mask Header
  751. if (!skipMask) {
  752. view = new DataView(input, fp, 16);
  753. data.mask = {};
  754. data.mask.numBlocksY = view.getUint32(0, true);
  755. data.mask.numBlocksX = view.getUint32(4, true);
  756. data.mask.numBytes = view.getUint32(8, true);
  757. data.mask.maxValue = view.getFloat32(12, true);
  758. fp += 16;
  759. // Mask Data
  760. if (data.mask.numBytes > 0) {
  761. var bitset = new Uint8Array(Math.ceil(data.width * data.height / 8));
  762. view = new DataView(input, fp, data.mask.numBytes);
  763. var cnt = view.getInt16(0, true);
  764. var ip = 2, op = 0;
  765. do {
  766. if (cnt > 0) {
  767. while (cnt--) { bitset[op++] = view.getUint8(ip++); }
  768. } else {
  769. var val = view.getUint8(ip++);
  770. cnt = -cnt;
  771. while (cnt--) { bitset[op++] = val; }
  772. }
  773. cnt = view.getInt16(ip, true);
  774. ip += 2;
  775. } while (ip < data.mask.numBytes);
  776. if ((cnt !== -32768) || (op < bitset.length)) {
  777. throw "Unexpected end of mask RLE encoding";
  778. }
  779. data.mask.bitset = bitset;
  780. fp += data.mask.numBytes;
  781. }
  782. else if ((data.mask.numBytes | data.mask.numBlocksY | data.mask.maxValue) === 0) { // Special case, all nodata
  783. data.mask.bitset = new Uint8Array(Math.ceil(data.width * data.height / 8));
  784. }
  785. }
  786. // Pixel Header
  787. view = new DataView(input, fp, 16);
  788. data.pixels = {};
  789. data.pixels.numBlocksY = view.getUint32(0, true);
  790. data.pixels.numBlocksX = view.getUint32(4, true);
  791. data.pixels.numBytes = view.getUint32(8, true);
  792. data.pixels.maxValue = view.getFloat32(12, true);
  793. fp += 16;
  794. var numBlocksX = data.pixels.numBlocksX;
  795. var numBlocksY = data.pixels.numBlocksY;
  796. // the number of blocks specified in the header does not take into account the blocks at the end of
  797. // each row/column with a special width/height that make the image complete in case the width is not
  798. // evenly divisible by the number of blocks.
  799. var actualNumBlocksX = numBlocksX + ((data.width % numBlocksX) > 0 ? 1 : 0);
  800. var actualNumBlocksY = numBlocksY + ((data.height % numBlocksY) > 0 ? 1 : 0);
  801. data.pixels.blocks = new Array(actualNumBlocksX * actualNumBlocksY);
  802. var blockI = 0;
  803. for (var blockY = 0; blockY < actualNumBlocksY; blockY++) {
  804. for (var blockX = 0; blockX < actualNumBlocksX; blockX++) {
  805. // Block
  806. var size = 0;
  807. var bytesLeft = input.byteLength - fp;
  808. view = new DataView(input, fp, Math.min(10, bytesLeft));
  809. var block = {};
  810. data.pixels.blocks[blockI++] = block;
  811. var headerByte = view.getUint8(0); size++;
  812. block.encoding = headerByte & 63;
  813. if (block.encoding > 3) {
  814. throw "Invalid block encoding (" + block.encoding + ")";
  815. }
  816. if (block.encoding === 2) {
  817. fp++;
  818. continue;
  819. }
  820. if ((headerByte !== 0) && (headerByte !== 2)) {
  821. headerByte >>= 6;
  822. block.offsetType = headerByte;
  823. if (headerByte === 2) {
  824. block.offset = view.getInt8(1); size++;
  825. } else if (headerByte === 1) {
  826. block.offset = view.getInt16(1, true); size += 2;
  827. } else if (headerByte === 0) {
  828. block.offset = view.getFloat32(1, true); size += 4;
  829. } else {
  830. throw "Invalid block offset type";
  831. }
  832. if (block.encoding === 1) {
  833. headerByte = view.getUint8(size); size++;
  834. block.bitsPerPixel = headerByte & 63;
  835. headerByte >>= 6;
  836. block.numValidPixelsType = headerByte;
  837. if (headerByte === 2) {
  838. block.numValidPixels = view.getUint8(size); size++;
  839. } else if (headerByte === 1) {
  840. block.numValidPixels = view.getUint16(size, true); size += 2;
  841. } else if (headerByte === 0) {
  842. block.numValidPixels = view.getUint32(size, true); size += 4;
  843. } else {
  844. throw "Invalid valid pixel count type";
  845. }
  846. }
  847. }
  848. fp += size;
  849. if (block.encoding === 3) {
  850. continue;
  851. }
  852. var arrayBuf, store8;
  853. if (block.encoding === 0) {
  854. var numPixels = (data.pixels.numBytes - 1) / 4;
  855. if (numPixels !== Math.floor(numPixels)) {
  856. throw "uncompressed block has invalid length";
  857. }
  858. arrayBuf = new ArrayBuffer(numPixels * 4);
  859. store8 = new Uint8Array(arrayBuf);
  860. store8.set(new Uint8Array(input, fp, numPixels * 4));
  861. var rawData = new Float32Array(arrayBuf);
  862. block.rawData = rawData;
  863. fp += numPixels * 4;
  864. } else if (block.encoding === 1) {
  865. var dataBytes = Math.ceil(block.numValidPixels * block.bitsPerPixel / 8);
  866. var dataWords = Math.ceil(dataBytes / 4);
  867. arrayBuf = new ArrayBuffer(dataWords * 4);
  868. store8 = new Uint8Array(arrayBuf);
  869. store8.set(new Uint8Array(input, fp, dataBytes));
  870. block.stuffedData = new Uint32Array(arrayBuf);
  871. fp += dataBytes;
  872. }
  873. }
  874. }
  875. data.eofOffset = fp;
  876. return data;
  877. };
  878. var unstuff = function(src, bitsPerPixel, numPixels, offset, scale, dest, maxValue) {
  879. var bitMask = (1 << bitsPerPixel) - 1;
  880. var i = 0, o;
  881. var bitsLeft = 0;
  882. var n, buffer;
  883. var nmax = Math.ceil((maxValue - offset) / scale);
  884. // get rid of trailing bytes that are already part of next block
  885. var numInvalidTailBytes = src.length * 4 - Math.ceil(bitsPerPixel * numPixels / 8);
  886. src[src.length - 1] <<= 8 * numInvalidTailBytes;
  887. for (o = 0; o < numPixels; o++) {
  888. if (bitsLeft === 0) {
  889. buffer = src[i++];
  890. bitsLeft = 32;
  891. }
  892. if (bitsLeft >= bitsPerPixel) {
  893. n = (buffer >>> (bitsLeft - bitsPerPixel)) & bitMask;
  894. bitsLeft -= bitsPerPixel;
  895. } else {
  896. var missingBits = (bitsPerPixel - bitsLeft);
  897. n = ((buffer & bitMask) << missingBits) & bitMask;
  898. buffer = src[i++];
  899. bitsLeft = 32 - missingBits;
  900. n += (buffer >>> bitsLeft);
  901. }
  902. //pixel values may exceed max due to quantization
  903. dest[o] = n < nmax ? offset + n * scale : maxValue;
  904. }
  905. return dest;
  906. };
  907. return CntZImage;
  908. })();
  909. //version 2. Supports 2.1, 2.2, 2.3
  910. var Lerc2Decode = (function() {
  911. // Note: currently, this module only has an implementation for decoding LERC data, not encoding. The name of
  912. // the class was chosen to be future proof, following LercDecode.
  913. /*****************************************
  914. * private static class bitsutffer used by Lerc2Decode
  915. *******************************************/
  916. var BitStuffer = {
  917. //methods ending with 2 are for the new byte order used by Lerc2.3 and above.
  918. //originalUnstuff is used to unpack Huffman code table. code is duplicated to unstuffx for performance reasons.
  919. unstuff: function(src, dest, bitsPerPixel, numPixels, lutArr, offset, scale, maxValue) {
  920. var bitMask = (1 << bitsPerPixel) - 1;
  921. var i = 0, o;
  922. var bitsLeft = 0;
  923. var n, buffer, missingBits, nmax;
  924. // get rid of trailing bytes that are already part of next block
  925. var numInvalidTailBytes = src.length * 4 - Math.ceil(bitsPerPixel * numPixels / 8);
  926. src[src.length - 1] <<= 8 * numInvalidTailBytes;
  927. if (lutArr) {
  928. for (o = 0; o < numPixels; o++) {
  929. if (bitsLeft === 0) {
  930. buffer = src[i++];
  931. bitsLeft = 32;
  932. }
  933. if (bitsLeft >= bitsPerPixel) {
  934. n = (buffer >>> (bitsLeft - bitsPerPixel)) & bitMask;
  935. bitsLeft -= bitsPerPixel;
  936. }
  937. else {
  938. missingBits = (bitsPerPixel - bitsLeft);
  939. n = ((buffer & bitMask) << missingBits) & bitMask;
  940. buffer = src[i++];
  941. bitsLeft = 32 - missingBits;
  942. n += (buffer >>> bitsLeft);
  943. }
  944. dest[o] = lutArr[n];//offset + lutArr[n] * scale;
  945. }
  946. }
  947. else {
  948. nmax = Math.ceil((maxValue - offset) / scale);
  949. for (o = 0; o < numPixels; o++) {
  950. if (bitsLeft === 0) {
  951. buffer = src[i++];
  952. bitsLeft = 32;
  953. }
  954. if (bitsLeft >= bitsPerPixel) {
  955. n = (buffer >>> (bitsLeft - bitsPerPixel)) & bitMask;
  956. bitsLeft -= bitsPerPixel;
  957. }
  958. else {
  959. missingBits = (bitsPerPixel - bitsLeft);
  960. n = ((buffer & bitMask) << missingBits) & bitMask;
  961. buffer = src[i++];
  962. bitsLeft = 32 - missingBits;
  963. n += (buffer >>> bitsLeft);
  964. }
  965. //pixel values may exceed max due to quantization
  966. dest[o] = n < nmax ? offset + n * scale : maxValue;
  967. }
  968. }
  969. },
  970. unstuffLUT: function(src, bitsPerPixel, numPixels, offset, scale, maxValue) {
  971. var bitMask = (1 << bitsPerPixel) - 1;
  972. var i = 0, o = 0, missingBits = 0, bitsLeft = 0, n = 0;
  973. var buffer;
  974. var dest = [];
  975. // get rid of trailing bytes that are already part of next block
  976. var numInvalidTailBytes = src.length * 4 - Math.ceil(bitsPerPixel * numPixels / 8);
  977. src[src.length - 1] <<= 8 * numInvalidTailBytes;
  978. var nmax = Math.ceil((maxValue - offset) / scale);
  979. for (o = 0; o < numPixels; o++) {
  980. if (bitsLeft === 0) {
  981. buffer = src[i++];
  982. bitsLeft = 32;
  983. }
  984. if (bitsLeft >= bitsPerPixel) {
  985. n = (buffer >>> (bitsLeft - bitsPerPixel)) & bitMask;
  986. bitsLeft -= bitsPerPixel;
  987. } else {
  988. missingBits = (bitsPerPixel - bitsLeft);
  989. n = ((buffer & bitMask) << missingBits) & bitMask;
  990. buffer = src[i++];
  991. bitsLeft = 32 - missingBits;
  992. n += (buffer >>> bitsLeft);
  993. }
  994. //dest.push(n);
  995. dest[o] = n < nmax ? offset + n * scale : maxValue;
  996. }
  997. dest.unshift(offset);//1st one
  998. return dest;
  999. },
  1000. unstuff2: function(src, dest, bitsPerPixel, numPixels, lutArr, offset, scale, maxValue) {
  1001. var bitMask = (1 << bitsPerPixel) - 1;
  1002. var i = 0, o;
  1003. var bitsLeft = 0, bitPos = 0;
  1004. var n, buffer, missingBits;
  1005. if (lutArr) {
  1006. for (o = 0; o < numPixels; o++) {
  1007. if (bitsLeft === 0) {
  1008. buffer = src[i++];
  1009. bitsLeft = 32;
  1010. bitPos = 0;
  1011. }
  1012. if (bitsLeft >= bitsPerPixel) {
  1013. n = ((buffer >>> bitPos) & bitMask);
  1014. bitsLeft -= bitsPerPixel;
  1015. bitPos += bitsPerPixel;
  1016. } else {
  1017. missingBits = (bitsPerPixel - bitsLeft);
  1018. n = (buffer >>> bitPos) & bitMask;
  1019. buffer = src[i++];
  1020. bitsLeft = 32 - missingBits;
  1021. n |= (buffer & ((1 << missingBits) - 1)) << (bitsPerPixel - missingBits);
  1022. bitPos = missingBits;
  1023. }
  1024. dest[o] = lutArr[n];
  1025. }
  1026. }
  1027. else {
  1028. var nmax = Math.ceil((maxValue - offset) / scale);
  1029. for (o = 0; o < numPixels; o++) {
  1030. if (bitsLeft === 0) {
  1031. buffer = src[i++];
  1032. bitsLeft = 32;
  1033. bitPos = 0;
  1034. }
  1035. if (bitsLeft >= bitsPerPixel) {
  1036. //no unsigned left shift
  1037. n = ((buffer >>> bitPos) & bitMask);
  1038. bitsLeft -= bitsPerPixel;
  1039. bitPos += bitsPerPixel;
  1040. } else {
  1041. missingBits = (bitsPerPixel - bitsLeft);
  1042. n = (buffer >>> bitPos) & bitMask;//((buffer & bitMask) << missingBits) & bitMask;
  1043. buffer = src[i++];
  1044. bitsLeft = 32 - missingBits;
  1045. n |= (buffer & ((1 << missingBits) - 1)) << (bitsPerPixel - missingBits);
  1046. bitPos = missingBits;
  1047. }
  1048. //pixel values may exceed max due to quantization
  1049. dest[o] = n < nmax ? offset + n * scale : maxValue;
  1050. }
  1051. }
  1052. return dest;
  1053. },
  1054. unstuffLUT2: function(src, bitsPerPixel, numPixels, offset, scale, maxValue) {
  1055. var bitMask = (1 << bitsPerPixel) - 1;
  1056. var i = 0, o = 0, missingBits = 0, bitsLeft = 0, n = 0, bitPos = 0;
  1057. var buffer;
  1058. var dest = [];
  1059. var nmax = Math.ceil((maxValue - offset) / scale);
  1060. for (o = 0; o < numPixels; o++) {
  1061. if (bitsLeft === 0) {
  1062. buffer = src[i++];
  1063. bitsLeft = 32;
  1064. bitPos = 0;
  1065. }
  1066. if (bitsLeft >= bitsPerPixel) {
  1067. //no unsigned left shift
  1068. n = ((buffer >>> bitPos) & bitMask);
  1069. bitsLeft -= bitsPerPixel;
  1070. bitPos += bitsPerPixel;
  1071. } else {
  1072. missingBits = (bitsPerPixel - bitsLeft);
  1073. n = (buffer >>> bitPos) & bitMask;//((buffer & bitMask) << missingBits) & bitMask;
  1074. buffer = src[i++];
  1075. bitsLeft = 32 - missingBits;
  1076. n |= (buffer & ((1 << missingBits) - 1)) << (bitsPerPixel - missingBits);
  1077. bitPos = missingBits;
  1078. }
  1079. //dest.push(n);
  1080. dest[o] = n < nmax ? offset + n * scale : maxValue;
  1081. }
  1082. dest.unshift(offset);
  1083. return dest;
  1084. },
  1085. originalUnstuff: function(src, dest, bitsPerPixel, numPixels) {
  1086. var bitMask = (1 << bitsPerPixel) - 1;
  1087. var i = 0, o;
  1088. var bitsLeft = 0;
  1089. var n, buffer, missingBits;
  1090. // get rid of trailing bytes that are already part of next block
  1091. var numInvalidTailBytes = src.length * 4 - Math.ceil(bitsPerPixel * numPixels / 8);
  1092. src[src.length - 1] <<= 8 * numInvalidTailBytes;
  1093. for (o = 0; o < numPixels; o++) {
  1094. if (bitsLeft === 0) {
  1095. buffer = src[i++];
  1096. bitsLeft = 32;
  1097. }
  1098. if (bitsLeft >= bitsPerPixel) {
  1099. n = (buffer >>> (bitsLeft - bitsPerPixel)) & bitMask;
  1100. bitsLeft -= bitsPerPixel;
  1101. }
  1102. else {
  1103. missingBits = (bitsPerPixel - bitsLeft);
  1104. n = ((buffer & bitMask) << missingBits) & bitMask;
  1105. buffer = src[i++];
  1106. bitsLeft = 32 - missingBits;
  1107. n += (buffer >>> bitsLeft);
  1108. }
  1109. dest[o] = n;
  1110. }
  1111. return dest;
  1112. },
  1113. originalUnstuff2: function(src, dest, bitsPerPixel, numPixels) {
  1114. var bitMask = (1 << bitsPerPixel) - 1;
  1115. var i = 0, o;
  1116. var bitsLeft = 0, bitPos = 0;
  1117. var n, buffer, missingBits;
  1118. //micro-optimizations
  1119. for (o = 0; o < numPixels; o++) {
  1120. if (bitsLeft === 0) {
  1121. buffer = src[i++];
  1122. bitsLeft = 32;
  1123. bitPos = 0;
  1124. }
  1125. if (bitsLeft >= bitsPerPixel) {
  1126. //no unsigned left shift
  1127. n = ((buffer >>> bitPos) & bitMask);
  1128. bitsLeft -= bitsPerPixel;
  1129. bitPos += bitsPerPixel;
  1130. } else {
  1131. missingBits = (bitsPerPixel - bitsLeft);
  1132. n = (buffer >>> bitPos) & bitMask;//((buffer & bitMask) << missingBits) & bitMask;
  1133. buffer = src[i++];
  1134. bitsLeft = 32 - missingBits;
  1135. n |= (buffer & ((1 << missingBits) - 1)) << (bitsPerPixel - missingBits);
  1136. bitPos = missingBits;
  1137. }
  1138. dest[o] = n;
  1139. }
  1140. return dest;
  1141. }
  1142. };
  1143. /*****************************************
  1144. *private static class used by Lerc2Decode
  1145. ******************************************/
  1146. var Lerc2Helpers = {
  1147. HUFFMAN_LUT_BITS_MAX: 12, //use 2^12 lut, treat it like constant
  1148. computeChecksumFletcher32: function(input) {
  1149. var sum1 = 0xffff, sum2 = 0xffff;
  1150. var len = input.length;
  1151. var words = Math.floor(len / 2);
  1152. var i = 0;
  1153. while (words) {
  1154. var tlen = (words >= 359) ? 359 : words;
  1155. words -= tlen;
  1156. do {
  1157. sum1 += (input[i++] << 8);
  1158. sum2 += sum1 += input[i++];
  1159. } while (--tlen);
  1160. sum1 = (sum1 & 0xffff) + (sum1 >>> 16);
  1161. sum2 = (sum2 & 0xffff) + (sum2 >>> 16);
  1162. }
  1163. // add the straggler byte if it exists
  1164. if (len & 1) {
  1165. sum2 += sum1 += (input[i] << 8);
  1166. }
  1167. // second reduction step to reduce sums to 16 bits
  1168. sum1 = (sum1 & 0xffff) + (sum1 >>> 16);
  1169. sum2 = (sum2 & 0xffff) + (sum2 >>> 16);
  1170. return (sum2 << 16 | sum1) >>> 0;
  1171. },
  1172. readHeaderInfo: function(input, data) {
  1173. var ptr = data.ptr;
  1174. var fileIdView = new Uint8Array(input, ptr, 6);
  1175. var headerInfo = {};
  1176. headerInfo.fileIdentifierString = String.fromCharCode.apply(null, fileIdView);
  1177. if (headerInfo.fileIdentifierString.lastIndexOf("Lerc2", 0) !== 0) {
  1178. throw "Unexpected file identifier string (expect Lerc2 ): " + headerInfo.fileIdentifierString;
  1179. }
  1180. ptr += 6;
  1181. var view = new DataView(input, ptr, 8);
  1182. var fileVersion = view.getInt32(0, true);
  1183. headerInfo.fileVersion = fileVersion;
  1184. ptr += 4;
  1185. if (fileVersion >= 3) {
  1186. headerInfo.checksum = view.getUint32(4, true); //nrows
  1187. ptr += 4;
  1188. }
  1189. //keys start from here
  1190. view = new DataView(input, ptr, 12);
  1191. headerInfo.height = view.getUint32(0, true); //nrows
  1192. headerInfo.width = view.getUint32(4, true); //ncols
  1193. ptr += 8;
  1194. if (fileVersion >= 4) {
  1195. headerInfo.numDims = view.getUint32(8, true);
  1196. ptr += 4;
  1197. }
  1198. else {
  1199. headerInfo.numDims = 1;
  1200. }
  1201. view = new DataView(input, ptr, 40);
  1202. headerInfo.numValidPixel = view.getUint32(0, true);
  1203. headerInfo.microBlockSize = view.getInt32(4, true);
  1204. headerInfo.blobSize = view.getInt32(8, true);
  1205. headerInfo.imageType = view.getInt32(12, true);
  1206. headerInfo.maxZError = view.getFloat64(16, true);
  1207. headerInfo.zMin = view.getFloat64(24, true);
  1208. headerInfo.zMax = view.getFloat64(32, true);
  1209. ptr += 40;
  1210. data.headerInfo = headerInfo;
  1211. data.ptr = ptr;
  1212. var checksum, keyLength;
  1213. if (fileVersion >= 3) {
  1214. keyLength = fileVersion >= 4 ? 52 : 48;
  1215. checksum = this.computeChecksumFletcher32(new Uint8Array(input, ptr - keyLength, headerInfo.blobSize - 14));
  1216. if (checksum !== headerInfo.checksum) {
  1217. throw "Checksum failed.";
  1218. }
  1219. }
  1220. return true;
  1221. },
  1222. checkMinMaxRanges: function(input, data) {
  1223. var headerInfo = data.headerInfo;
  1224. var OutPixelTypeArray = this.getDataTypeArray(headerInfo.imageType);
  1225. var rangeBytes = headerInfo.numDims * this.getDataTypeSize(headerInfo.imageType);
  1226. var minValues = this.readSubArray(input, data.ptr, OutPixelTypeArray, rangeBytes);
  1227. var maxValues = this.readSubArray(input, data.ptr + rangeBytes, OutPixelTypeArray, rangeBytes);
  1228. data.ptr += (2 * rangeBytes);
  1229. var i, equal = true;
  1230. for (i = 0; i < headerInfo.numDims; i++) {
  1231. if (minValues[i] !== maxValues[i]) {
  1232. equal = false;
  1233. break;
  1234. }
  1235. }
  1236. headerInfo.minValues = minValues;
  1237. headerInfo.maxValues = maxValues;
  1238. return equal;
  1239. },
  1240. readSubArray: function(input, ptr, OutPixelTypeArray, numBytes) {
  1241. var rawData;
  1242. if (OutPixelTypeArray === Uint8Array) {
  1243. rawData = new Uint8Array(input, ptr, numBytes);
  1244. }
  1245. else {
  1246. var arrayBuf = new ArrayBuffer(numBytes);
  1247. var store8 = new Uint8Array(arrayBuf);
  1248. store8.set(new Uint8Array(input, ptr, numBytes));
  1249. rawData = new OutPixelTypeArray(arrayBuf);
  1250. }
  1251. return rawData;
  1252. },
  1253. readMask: function(input, data) {
  1254. var ptr = data.ptr;
  1255. var headerInfo = data.headerInfo;
  1256. var numPixels = headerInfo.width * headerInfo.height;
  1257. var numValidPixel = headerInfo.numValidPixel;
  1258. var view = new DataView(input, ptr, 4);
  1259. var mask = {};
  1260. mask.numBytes = view.getUint32(0, true);
  1261. ptr += 4;
  1262. // Mask Data
  1263. if ((0 === numValidPixel || numPixels === numValidPixel) && 0 !== mask.numBytes) {
  1264. throw ("invalid mask");
  1265. }
  1266. var bitset, resultMask;
  1267. if (numValidPixel === 0) {
  1268. bitset = new Uint8Array(Math.ceil(numPixels / 8));
  1269. mask.bitset = bitset;
  1270. resultMask = new Uint8Array(numPixels);
  1271. data.pixels.resultMask = resultMask;
  1272. ptr += mask.numBytes;
  1273. }// ????? else if (data.mask.numBytes > 0 && data.mask.numBytes< data.numValidPixel) {
  1274. else if (mask.numBytes > 0) {
  1275. bitset = new Uint8Array(Math.ceil(numPixels / 8));
  1276. view = new DataView(input, ptr, mask.numBytes);
  1277. var cnt = view.getInt16(0, true);
  1278. var ip = 2, op = 0, val = 0;
  1279. do {
  1280. if (cnt > 0) {
  1281. while (cnt--) { bitset[op++] = view.getUint8(ip++); }
  1282. } else {
  1283. val = view.getUint8(ip++);
  1284. cnt = -cnt;
  1285. while (cnt--) { bitset[op++] = val; }
  1286. }
  1287. cnt = view.getInt16(ip, true);
  1288. ip += 2;
  1289. } while (ip < mask.numBytes);
  1290. if ((cnt !== -32768) || (op < bitset.length)) {
  1291. throw "Unexpected end of mask RLE encoding";
  1292. }
  1293. resultMask = new Uint8Array(numPixels);
  1294. var mb = 0, k = 0;
  1295. for (k = 0; k < numPixels; k++) {
  1296. if (k & 7) {
  1297. mb = bitset[k >> 3];
  1298. mb <<= k & 7;
  1299. }
  1300. else {
  1301. mb = bitset[k >> 3];
  1302. }
  1303. if (mb & 128) {
  1304. resultMask[k] = 1;
  1305. }
  1306. }
  1307. data.pixels.resultMask = resultMask;
  1308. mask.bitset = bitset;
  1309. ptr += mask.numBytes;
  1310. }
  1311. data.ptr = ptr;
  1312. data.mask = mask;
  1313. return true;
  1314. },
  1315. readDataOneSweep: function(input, data, OutPixelTypeArray) {
  1316. var ptr = data.ptr;
  1317. var headerInfo = data.headerInfo;
  1318. var numDims = headerInfo.numDims;
  1319. var numPixels = headerInfo.width * headerInfo.height;
  1320. var imageType = headerInfo.imageType;
  1321. var numBytes = headerInfo.numValidPixel * Lerc2Helpers.getDataTypeSize(imageType) * numDims;
  1322. //data.pixels.numBytes = numBytes;
  1323. var rawData;
  1324. var mask = data.pixels.resultMask;
  1325. if (OutPixelTypeArray === Uint8Array) {
  1326. rawData = new Uint8Array(input, ptr, numBytes);
  1327. }
  1328. else {
  1329. var arrayBuf = new ArrayBuffer(numBytes);
  1330. var store8 = new Uint8Array(arrayBuf);
  1331. store8.set(new Uint8Array(input, ptr, numBytes));
  1332. rawData = new OutPixelTypeArray(arrayBuf);
  1333. }
  1334. if (rawData.length === numPixels * numDims) {
  1335. data.pixels.resultPixels = rawData;
  1336. }
  1337. else //mask
  1338. {
  1339. data.pixels.resultPixels = new OutPixelTypeArray(numPixels * numDims);
  1340. var z = 0, k = 0, i = 0, nStart = 0;
  1341. if (numDims > 1) {
  1342. for (i=0; i < numDims; i++) {
  1343. nStart = i * numPixels;
  1344. for (k = 0; k < numPixels; k++) {
  1345. if (mask[k]) {
  1346. data.pixels.resultPixels[nStart + k] = rawData[z++];
  1347. }
  1348. }
  1349. }
  1350. }
  1351. else {
  1352. for (k = 0; k < numPixels; k++) {
  1353. if (mask[k]) {
  1354. data.pixels.resultPixels[k] = rawData[z++];
  1355. }
  1356. }
  1357. }
  1358. }
  1359. ptr += numBytes;
  1360. data.ptr = ptr; //return data;
  1361. return true;
  1362. },
  1363. readHuffmanTree: function(input, data) {
  1364. var BITS_MAX = this.HUFFMAN_LUT_BITS_MAX; //8 is slow for the large test image
  1365. //var size_max = 1 << BITS_MAX;
  1366. /* ************************
  1367. * reading code table
  1368. *************************/
  1369. var view = new DataView(input, data.ptr, 16);
  1370. data.ptr += 16;
  1371. var version = view.getInt32(0, true);
  1372. if (version < 2) {
  1373. throw "unsupported Huffman version";
  1374. }
  1375. var size = view.getInt32(4, true);
  1376. var i0 = view.getInt32(8, true);
  1377. var i1 = view.getInt32(12, true);
  1378. if (i0 >= i1) {
  1379. return false;
  1380. }
  1381. var blockDataBuffer = new Uint32Array(i1 - i0);
  1382. Lerc2Helpers.decodeBits(input, data, blockDataBuffer);
  1383. var codeTable = []; //size
  1384. var i, j, k, len;
  1385. for (i = i0; i < i1; i++) {
  1386. j = i - (i < size ? 0 : size);//wrap around
  1387. codeTable[j] = { first: blockDataBuffer[i - i0], second: null };
  1388. }
  1389. var dataBytes = input.byteLength - data.ptr;
  1390. var dataWords = Math.ceil(dataBytes / 4);
  1391. var arrayBuf = new ArrayBuffer(dataWords * 4);
  1392. var store8 = new Uint8Array(arrayBuf);
  1393. store8.set(new Uint8Array(input, data.ptr, dataBytes));
  1394. var stuffedData = new Uint32Array(arrayBuf); //must start from x*4
  1395. var bitPos = 0, word, srcPtr = 0;
  1396. word = stuffedData[0];
  1397. for (i = i0; i < i1; i++) {
  1398. j = i - (i < size ? 0 : size);//wrap around
  1399. len = codeTable[j].first;
  1400. if (len > 0) {
  1401. codeTable[j].second = (word << bitPos) >>> (32 - len);
  1402. if (32 - bitPos >= len) {
  1403. bitPos += len;
  1404. if (bitPos === 32) {
  1405. bitPos = 0;
  1406. srcPtr++;
  1407. word = stuffedData[srcPtr];
  1408. }
  1409. }
  1410. else {
  1411. bitPos += len - 32;
  1412. srcPtr++;
  1413. word = stuffedData[srcPtr];
  1414. codeTable[j].second |= word >>> (32 - bitPos);
  1415. }
  1416. }
  1417. }
  1418. //finished reading code table
  1419. /* ************************
  1420. * building lut
  1421. *************************/
  1422. var numBitsLUT = 0, numBitsLUTQick = 0;
  1423. var tree = new TreeNode();
  1424. for (i = 0; i < codeTable.length; i++) {
  1425. if (codeTable[i] !== undefined) {
  1426. numBitsLUT = Math.max(numBitsLUT, codeTable[i].first);
  1427. }
  1428. }
  1429. if (numBitsLUT >= BITS_MAX) {
  1430. numBitsLUTQick = BITS_MAX;
  1431. }
  1432. else {
  1433. numBitsLUTQick = numBitsLUT;
  1434. }
  1435. if (numBitsLUT >= 30) {
  1436. console.log("WARning, large NUM LUT BITS IS " + numBitsLUT);
  1437. }
  1438. var decodeLut = [], entry, code, numEntries, jj, currentBit, node;
  1439. for (i = i0; i < i1; i++) {
  1440. j = i - (i < size ? 0 : size);//wrap around
  1441. len = codeTable[j].first;
  1442. if (len > 0) {
  1443. entry = [len, j];
  1444. if (len <= numBitsLUTQick) {
  1445. code = codeTable[j].second << (numBitsLUTQick - len);
  1446. numEntries = 1 << (numBitsLUTQick - len);
  1447. for (k = 0; k < numEntries; k++) {
  1448. decodeLut[code | k] = entry;
  1449. }
  1450. }
  1451. else {
  1452. //build tree
  1453. code = codeTable[j].second;
  1454. node = tree;
  1455. for (jj = len - 1; jj >= 0; jj--) {
  1456. currentBit = code >>> jj & 1; //no left shift as length could be 30,31
  1457. if (currentBit) {
  1458. if (!node.right) {
  1459. node.right = new TreeNode();
  1460. }
  1461. node = node.right;
  1462. }
  1463. else {
  1464. if (!node.left) {
  1465. node.left = new TreeNode();
  1466. }
  1467. node = node.left;
  1468. }
  1469. if (jj === 0 && !node.val) {
  1470. node.val = entry[1];
  1471. }
  1472. }
  1473. }
  1474. }
  1475. }
  1476. return {
  1477. decodeLut: decodeLut,
  1478. numBitsLUTQick: numBitsLUTQick,
  1479. numBitsLUT: numBitsLUT,
  1480. tree: tree,
  1481. stuffedData: stuffedData,
  1482. srcPtr: srcPtr,
  1483. bitPos: bitPos
  1484. };
  1485. },
  1486. readHuffman: function(input, data, OutPixelTypeArray) {
  1487. var headerInfo = data.headerInfo;
  1488. var numDims = headerInfo.numDims;
  1489. var height = data.headerInfo.height;
  1490. var width = data.headerInfo.width;
  1491. var numPixels = width * height;
  1492. //var size_max = 1 << BITS_MAX;
  1493. /* ************************
  1494. * reading huffman structure info
  1495. *************************/
  1496. var huffmanInfo = this.readHuffmanTree(input, data);
  1497. var decodeLut = huffmanInfo.decodeLut;
  1498. var tree = huffmanInfo.tree;
  1499. //stuffedData includes huffman headers
  1500. var stuffedData = huffmanInfo.stuffedData;
  1501. var srcPtr = huffmanInfo.srcPtr;
  1502. var bitPos = huffmanInfo.bitPos;
  1503. var numBitsLUTQick = huffmanInfo.numBitsLUTQick;
  1504. var numBitsLUT = huffmanInfo.numBitsLUT;
  1505. var offset = data.headerInfo.imageType === 0 ? 128 : 0;
  1506. /*************************
  1507. * decode
  1508. ***************************/
  1509. var node, val, delta, mask = data.pixels.resultMask, valTmp, valTmpQuick, currentBit;
  1510. var i, j, k, ii;
  1511. var prevVal = 0;
  1512. if (bitPos > 0) {
  1513. srcPtr++;
  1514. bitPos = 0;
  1515. }
  1516. var word = stuffedData[srcPtr];
  1517. var deltaEncode = data.encodeMode === 1;
  1518. var resultPixelsAllDim = new OutPixelTypeArray(numPixels * numDims);
  1519. var resultPixels = resultPixelsAllDim;
  1520. var iDim;
  1521. for (iDim = 0; iDim < headerInfo.numDims; iDim++) {
  1522. if (numDims > 1) {
  1523. //get the mem block of current dimension
  1524. resultPixels = new OutPixelTypeArray(resultPixelsAllDim.buffer, numPixels * iDim, numPixels);
  1525. prevVal = 0;
  1526. }
  1527. if (data.headerInfo.numValidPixel === width * height) { //all valid
  1528. for (k = 0, i = 0; i < height; i++) {
  1529. for (j = 0; j < width; j++, k++) {
  1530. val = 0;
  1531. valTmp = (word << bitPos) >>> (32 - numBitsLUTQick);
  1532. valTmpQuick = valTmp;// >>> deltaBits;
  1533. if (32 - bitPos < numBitsLUTQick) {
  1534. valTmp |= ((stuffedData[srcPtr + 1]) >>> (64 - bitPos - numBitsLUTQick));
  1535. valTmpQuick = valTmp;// >>> deltaBits;
  1536. }
  1537. if (decodeLut[valTmpQuick]) // if there, move the correct number of bits and done
  1538. {
  1539. val = decodeLut[valTmpQuick][1];
  1540. bitPos += decodeLut[valTmpQuick][0];
  1541. }
  1542. else {
  1543. valTmp = (word << bitPos) >>> (32 - numBitsLUT);
  1544. valTmpQuick = valTmp;// >>> deltaBits;
  1545. if (32 - bitPos < numBitsLUT) {
  1546. valTmp |= ((stuffedData[srcPtr + 1]) >>> (64 - bitPos - numBitsLUT));
  1547. valTmpQuick = valTmp;// >>> deltaBits;
  1548. }
  1549. node = tree;
  1550. for (ii = 0; ii < numBitsLUT; ii++) {
  1551. currentBit = valTmp >>> (numBitsLUT - ii - 1) & 1;
  1552. node = currentBit ? node.right : node.left;
  1553. if (!(node.left || node.right)) {
  1554. val = node.val;
  1555. bitPos = bitPos + ii + 1;
  1556. break;
  1557. }
  1558. }
  1559. }
  1560. if (bitPos >= 32) {
  1561. bitPos -= 32;
  1562. srcPtr++;
  1563. word = stuffedData[srcPtr];
  1564. }
  1565. delta = val - offset;
  1566. if (deltaEncode) {
  1567. if (j > 0) {
  1568. delta += prevVal; // use overflow
  1569. }
  1570. else if (i > 0) {
  1571. delta += resultPixels[k - width];
  1572. }
  1573. else {
  1574. delta += prevVal;
  1575. }
  1576. delta &= 0xFF; //overflow
  1577. resultPixels[k] = delta;//overflow
  1578. prevVal = delta;
  1579. }
  1580. else {
  1581. resultPixels[k] = delta;
  1582. }
  1583. }
  1584. }
  1585. }
  1586. else { //not all valid, use mask
  1587. for (k = 0, i = 0; i < height; i++) {
  1588. for (j = 0; j < width; j++, k++) {
  1589. if (mask[k]) {
  1590. val = 0;
  1591. valTmp = (word << bitPos) >>> (32 - numBitsLUTQick);
  1592. valTmpQuick = valTmp;// >>> deltaBits;
  1593. if (32 - bitPos < numBitsLUTQick) {
  1594. valTmp |= ((stuffedData[srcPtr + 1]) >>> (64 - bitPos - numBitsLUTQick));
  1595. valTmpQuick = valTmp;// >>> deltaBits;
  1596. }
  1597. if (decodeLut[valTmpQuick]) // if there, move the correct number of bits and done
  1598. {
  1599. val = decodeLut[valTmpQuick][1];
  1600. bitPos += decodeLut[valTmpQuick][0];
  1601. }
  1602. else {
  1603. valTmp = (word << bitPos) >>> (32 - numBitsLUT);
  1604. valTmpQuick = valTmp;// >>> deltaBits;
  1605. if (32 - bitPos < numBitsLUT) {
  1606. valTmp |= ((stuffedData[srcPtr + 1]) >>> (64 - bitPos - numBitsLUT));
  1607. valTmpQuick = valTmp;// >>> deltaBits;
  1608. }
  1609. node = tree;
  1610. for (ii = 0; ii < numBitsLUT; ii++) {
  1611. currentBit = valTmp >>> (numBitsLUT - ii - 1) & 1;
  1612. node = currentBit ? node.right : node.left;
  1613. if (!(node.left || node.right)) {
  1614. val = node.val;
  1615. bitPos = bitPos + ii + 1;
  1616. break;
  1617. }
  1618. }
  1619. }
  1620. if (bitPos >= 32) {
  1621. bitPos -= 32;
  1622. srcPtr++;
  1623. word = stuffedData[srcPtr];
  1624. }
  1625. delta = val - offset;
  1626. if (deltaEncode) {
  1627. if (j > 0 && mask[k - 1]) {
  1628. delta += prevVal; // use overflow
  1629. }
  1630. else if (i > 0 && mask[k - width]) {
  1631. delta += resultPixels[k - width];
  1632. }
  1633. else {
  1634. delta += prevVal;
  1635. }
  1636. delta &= 0xFF; //overflow
  1637. resultPixels[k] = delta;//overflow
  1638. prevVal = delta;
  1639. }
  1640. else {
  1641. resultPixels[k] = delta;
  1642. }
  1643. }
  1644. }
  1645. }
  1646. }
  1647. data.ptr = data.ptr + (srcPtr + 1) * 4 + (bitPos > 0 ? 4 : 0);
  1648. }
  1649. data.pixels.resultPixels = resultPixelsAllDim;
  1650. },
  1651. decodeBits: function(input, data, blockDataBuffer, offset, iDim) {
  1652. {
  1653. //bitstuff encoding is 3
  1654. var headerInfo = data.headerInfo;
  1655. var fileVersion = headerInfo.fileVersion;
  1656. //var block = {};
  1657. var blockPtr = 0;
  1658. var view = new DataView(input, data.ptr, 5);//to do
  1659. var headerByte = view.getUint8(0);
  1660. blockPtr++;
  1661. var bits67 = headerByte >> 6;
  1662. var n = (bits67 === 0) ? 4 : 3 - bits67;
  1663. var doLut = (headerByte & 32) > 0 ? true : false;//5th bit
  1664. var numBits = headerByte & 31;
  1665. var numElements = 0;
  1666. if (n === 1) {
  1667. numElements = view.getUint8(blockPtr); blockPtr++;
  1668. } else if (n === 2) {
  1669. numElements = view.getUint16(blockPtr, true); blockPtr += 2;
  1670. } else if (n === 4) {
  1671. numElements = view.getUint32(blockPtr, true); blockPtr += 4;
  1672. } else {
  1673. throw "Invalid valid pixel count type";
  1674. }
  1675. //fix: huffman codes are bit stuffed, but not bound by data's max value, so need to use originalUnstuff
  1676. //offset = offset || 0;
  1677. var scale = 2 * headerInfo.maxZError;
  1678. var stuffedData, arrayBuf, store8, dataBytes, dataWords;
  1679. var lutArr, lutData, lutBytes, bitsPerPixel;
  1680. var zMax = headerInfo.numDims > 1 ? headerInfo.maxValues[iDim] : headerInfo.zMax;
  1681. if (doLut) {
  1682. data.counter.lut++;
  1683. lutBytes = view.getUint8(blockPtr);
  1684. blockPtr++;
  1685. dataBytes = Math.ceil((lutBytes - 1) * numBits / 8);
  1686. dataWords = Math.ceil(dataBytes / 4);
  1687. arrayBuf = new ArrayBuffer(dataWords * 4);
  1688. store8 = new Uint8Array(arrayBuf);
  1689. data.ptr += blockPtr;
  1690. store8.set(new Uint8Array(input, data.ptr, dataBytes));
  1691. lutData = new Uint32Array(arrayBuf);
  1692. data.ptr += dataBytes;
  1693. bitsPerPixel = 0;
  1694. while ((lutBytes - 1) >>> bitsPerPixel) {
  1695. bitsPerPixel++;
  1696. }
  1697. dataBytes = Math.ceil(numElements * bitsPerPixel / 8);
  1698. dataWords = Math.ceil(dataBytes / 4);
  1699. arrayBuf = new ArrayBuffer(dataWords * 4);
  1700. store8 = new Uint8Array(arrayBuf);
  1701. store8.set(new Uint8Array(input, data.ptr, dataBytes));
  1702. stuffedData = new Uint32Array(arrayBuf);
  1703. data.ptr += dataBytes;
  1704. if (fileVersion >= 3) {
  1705. lutArr = BitStuffer.unstuffLUT2(lutData, numBits, lutBytes - 1, offset, scale, zMax);
  1706. }
  1707. else {
  1708. lutArr = BitStuffer.unstuffLUT(lutData, numBits, lutBytes - 1, offset, scale, zMax);
  1709. }
  1710. //lutArr.unshift(0);
  1711. if (fileVersion >= 3) {
  1712. //BitStuffer.unstuff2(block, blockDataBuffer, headerInfo.zMax);
  1713. BitStuffer.unstuff2(stuffedData, blockDataBuffer, bitsPerPixel, numElements, lutArr);
  1714. }
  1715. else {
  1716. BitStuffer.unstuff(stuffedData, blockDataBuffer, bitsPerPixel, numElements, lutArr);
  1717. }
  1718. }
  1719. else {
  1720. //console.debug("bitstuffer");
  1721. data.counter.bitstuffer++;
  1722. bitsPerPixel = numBits;
  1723. data.ptr += blockPtr;
  1724. if (bitsPerPixel > 0) {
  1725. dataBytes = Math.ceil(numElements * bitsPerPixel / 8);
  1726. dataWords = Math.ceil(dataBytes / 4);
  1727. arrayBuf = new ArrayBuffer(dataWords * 4);
  1728. store8 = new Uint8Array(arrayBuf);
  1729. store8.set(new Uint8Array(input, data.ptr, dataBytes));
  1730. stuffedData = new Uint32Array(arrayBuf);
  1731. data.ptr += dataBytes;
  1732. if (fileVersion >= 3) {
  1733. if (offset == null) {
  1734. BitStuffer.originalUnstuff2(stuffedData, blockDataBuffer, bitsPerPixel, numElements);
  1735. }
  1736. else {
  1737. BitStuffer.unstuff2(stuffedData, blockDataBuffer, bitsPerPixel, numElements, false, offset, scale, zMax);
  1738. }
  1739. }
  1740. else {
  1741. if (offset == null) {
  1742. BitStuffer.originalUnstuff(stuffedData, blockDataBuffer, bitsPerPixel, numElements);
  1743. }
  1744. else {
  1745. BitStuffer.unstuff(stuffedData, blockDataBuffer, bitsPerPixel, numElements, false, offset, scale, zMax);
  1746. }
  1747. }
  1748. }
  1749. }
  1750. }
  1751. },
  1752. readTiles: function(input, data, OutPixelTypeArray) {
  1753. var headerInfo = data.headerInfo;
  1754. var width = headerInfo.width;
  1755. var height = headerInfo.height;
  1756. var microBlockSize = headerInfo.microBlockSize;
  1757. var imageType = headerInfo.imageType;
  1758. var dataTypeSize = Lerc2Helpers.getDataTypeSize(imageType);
  1759. var numBlocksX = Math.ceil(width / microBlockSize);
  1760. var numBlocksY = Math.ceil(height / microBlockSize);
  1761. data.pixels.numBlocksY = numBlocksY;
  1762. data.pixels.numBlocksX = numBlocksX;
  1763. data.pixels.ptr = 0;
  1764. var row = 0, col = 0, blockY = 0, blockX = 0, thisBlockHeight = 0, thisBlockWidth = 0, bytesLeft = 0, headerByte = 0, bits67 = 0, testCode = 0, outPtr = 0, outStride = 0, numBytes = 0, bytesleft = 0, z = 0, blockPtr = 0;
  1765. var view, block, arrayBuf, store8, rawData;
  1766. var blockEncoding;
  1767. var blockDataBuffer = new OutPixelTypeArray(microBlockSize * microBlockSize);
  1768. var lastBlockHeight = (height % microBlockSize) || microBlockSize;
  1769. var lastBlockWidth = (width % microBlockSize) || microBlockSize;
  1770. var offsetType, offset;
  1771. var numDims = headerInfo.numDims, iDim;
  1772. var mask = data.pixels.resultMask;
  1773. var resultPixels = data.pixels.resultPixels;
  1774. for (blockY = 0; blockY < numBlocksY; blockY++) {
  1775. thisBlockHeight = (blockY !== numBlocksY - 1) ? microBlockSize : lastBlockHeight;
  1776. for (blockX = 0; blockX < numBlocksX; blockX++) {
  1777. //console.debug("y" + blockY + " x" + blockX);
  1778. thisBlockWidth = (blockX !== numBlocksX - 1) ? microBlockSize : lastBlockWidth;
  1779. outPtr = blockY * width * microBlockSize + blockX * microBlockSize;
  1780. outStride = width - thisBlockWidth;
  1781. for (iDim = 0; iDim < numDims; iDim++) {
  1782. if (numDims > 1) {
  1783. resultPixels = new OutPixelTypeArray(data.pixels.resultPixels.buffer, width * height * iDim * dataTypeSize, width * height);
  1784. }
  1785. bytesLeft = input.byteLength - data.ptr;
  1786. view = new DataView(input, data.ptr, Math.min(10, bytesLeft));
  1787. block = {};
  1788. blockPtr = 0;
  1789. headerByte = view.getUint8(0);
  1790. blockPtr++;
  1791. bits67 = (headerByte >> 6) & 0xFF;
  1792. testCode = (headerByte >> 2) & 15; // use bits 2345 for integrity check
  1793. if (testCode !== (((blockX * microBlockSize) >> 3) & 15)) {
  1794. throw "integrity issue";
  1795. //return false;
  1796. }
  1797. blockEncoding = headerByte & 3;
  1798. if (blockEncoding > 3) {
  1799. data.ptr += blockPtr;
  1800. throw "Invalid block encoding (" + blockEncoding + ")";
  1801. }
  1802. else if (blockEncoding === 2) { //constant 0
  1803. data.counter.constant++;
  1804. data.ptr += blockPtr;
  1805. continue;
  1806. }
  1807. else if (blockEncoding === 0) { //uncompressed
  1808. data.counter.uncompressed++;
  1809. data.ptr += blockPtr;
  1810. numBytes = thisBlockHeight * thisBlockWidth * dataTypeSize;
  1811. bytesleft = input.byteLength - data.ptr;
  1812. numBytes = numBytes < bytesleft ? numBytes : bytesleft;
  1813. //bit alignment
  1814. arrayBuf = new ArrayBuffer((numBytes % dataTypeSize) === 0 ? numBytes : (numBytes + dataTypeSize - numBytes % dataTypeSize));
  1815. store8 = new Uint8Array(arrayBuf);
  1816. store8.set(new Uint8Array(input, data.ptr, numBytes));
  1817. rawData = new OutPixelTypeArray(arrayBuf);
  1818. z = 0;
  1819. if (mask) {
  1820. for (row = 0; row < thisBlockHeight; row++) {
  1821. for (col = 0; col < thisBlockWidth; col++) {
  1822. if (mask[outPtr]) {
  1823. resultPixels[outPtr] = rawData[z++];
  1824. }
  1825. outPtr++;
  1826. }
  1827. outPtr += outStride;
  1828. }
  1829. }
  1830. else {//all valid
  1831. for (row = 0; row < thisBlockHeight; row++) {
  1832. for (col = 0; col < thisBlockWidth; col++) {
  1833. resultPixels[outPtr++] = rawData[z++];
  1834. }
  1835. outPtr += outStride;
  1836. }
  1837. }
  1838. data.ptr += z * dataTypeSize;
  1839. }
  1840. else { //1 or 3
  1841. offsetType = Lerc2Helpers.getDataTypeUsed(imageType, bits67);
  1842. offset = Lerc2Helpers.getOnePixel(block, blockPtr, offsetType, view);
  1843. blockPtr += Lerc2Helpers.getDataTypeSize(offsetType);
  1844. if (blockEncoding === 3) //constant offset value
  1845. {
  1846. data.ptr += blockPtr;
  1847. data.counter.constantoffset++;
  1848. //you can delete the following resultMask case in favor of performance because val is constant and users use nodata mask, otherwise nodatavalue post processing handles it too.
  1849. //while the above statement is true, we're not doing it as we want to keep invalid pixel value at 0 rather than arbitrary values
  1850. if (mask) {
  1851. for (row = 0; row < thisBlockHeight; row++) {
  1852. for (col = 0; col < thisBlockWidth; col++) {
  1853. if (mask[outPtr]) {
  1854. resultPixels[outPtr] = offset;
  1855. }
  1856. outPtr++;
  1857. }
  1858. outPtr += outStride;
  1859. }
  1860. }
  1861. else {
  1862. for (row = 0; row < thisBlockHeight; row++) {
  1863. for (col = 0; col < thisBlockWidth; col++) {
  1864. resultPixels[outPtr++] = offset;
  1865. }
  1866. outPtr += outStride;
  1867. }
  1868. }
  1869. }
  1870. else { //bitstuff encoding is 3
  1871. data.ptr += blockPtr;
  1872. //heavy lifting
  1873. Lerc2Helpers.decodeBits(input, data, blockDataBuffer, offset, iDim);
  1874. blockPtr = 0;
  1875. if (mask) {
  1876. for (row = 0; row < thisBlockHeight; row++) {
  1877. for (col = 0; col < thisBlockWidth; col++) {
  1878. if (mask[outPtr]) {
  1879. resultPixels[outPtr] = blockDataBuffer[blockPtr++];
  1880. }
  1881. outPtr++;
  1882. }
  1883. outPtr += outStride;
  1884. }
  1885. }
  1886. else {
  1887. for (row = 0; row < thisBlockHeight; row++) {
  1888. for (col = 0; col < thisBlockWidth; col++) {
  1889. resultPixels[outPtr++] = blockDataBuffer[blockPtr++];
  1890. }
  1891. outPtr += outStride;
  1892. }
  1893. }
  1894. }
  1895. }
  1896. }
  1897. }
  1898. }
  1899. },
  1900. /*****************
  1901. * private methods (helper methods)
  1902. *****************/
  1903. formatFileInfo: function(data) {
  1904. return {
  1905. "fileIdentifierString": data.headerInfo.fileIdentifierString,
  1906. "fileVersion": data.headerInfo.fileVersion,
  1907. "imageType": data.headerInfo.imageType,
  1908. "height": data.headerInfo.height,
  1909. "width": data.headerInfo.width,
  1910. "numValidPixel": data.headerInfo.numValidPixel,
  1911. "microBlockSize": data.headerInfo.microBlockSize,
  1912. "blobSize": data.headerInfo.blobSize,
  1913. "maxZError": data.headerInfo.maxZError,
  1914. "pixelType": Lerc2Helpers.getPixelType(data.headerInfo.imageType),
  1915. "eofOffset": data.eofOffset,
  1916. "mask": data.mask ? {
  1917. "numBytes": data.mask.numBytes
  1918. } : null,
  1919. "pixels": {
  1920. "numBlocksX": data.pixels.numBlocksX,
  1921. "numBlocksY": data.pixels.numBlocksY,
  1922. //"numBytes": data.pixels.numBytes,
  1923. "maxValue": data.headerInfo.zMax,
  1924. "minValue": data.headerInfo.zMin,
  1925. "noDataValue": data.noDataValue
  1926. }
  1927. };
  1928. },
  1929. constructConstantSurface: function(data) {
  1930. var val = data.headerInfo.zMax;
  1931. var numDims = data.headerInfo.numDims;
  1932. var numPixels = data.headerInfo.height * data.headerInfo.width;
  1933. var numPixelAllDims = numPixels * numDims;
  1934. var i=0, k = 0, nStart=0;
  1935. var mask = data.pixels.resultMask;
  1936. if (mask) {
  1937. if (numDims > 1) {
  1938. for (i=0; i < numDims; i++) {
  1939. nStart = i * numPixels;
  1940. for (k = 0; k < numPixels; k++) {
  1941. if (mask[k]) {
  1942. data.pixels.resultPixels[nStart + k] = val;
  1943. }
  1944. }
  1945. }
  1946. }
  1947. else {
  1948. for (k = 0; k < numPixels; k++) {
  1949. if (mask[k]) {
  1950. data.pixels.resultPixels[k] = val;
  1951. }
  1952. }
  1953. }
  1954. }
  1955. else {
  1956. if (data.pixels.resultPixels.fill) {
  1957. data.pixels.resultPixels.fill(val);
  1958. }
  1959. else {
  1960. for (k = 0; k < numPixelAllDims; k++) {
  1961. data.pixels.resultPixels[k] = val;
  1962. }
  1963. }
  1964. }
  1965. return;
  1966. },
  1967. getDataTypeArray: function(t) {
  1968. var tp;
  1969. switch (t) {
  1970. case 0: //char
  1971. tp = Int8Array;
  1972. break;
  1973. case 1: //byte
  1974. tp = Uint8Array;
  1975. break;
  1976. case 2: //short
  1977. tp = Int16Array;
  1978. break;
  1979. case 3: //ushort
  1980. tp = Uint16Array;
  1981. break;
  1982. case 4:
  1983. tp = Int32Array;
  1984. break;
  1985. case 5:
  1986. tp = Uint32Array;
  1987. break;
  1988. case 6:
  1989. tp = Float32Array;
  1990. break;
  1991. case 7:
  1992. tp = Float64Array;
  1993. break;
  1994. default:
  1995. tp = Float32Array;
  1996. }
  1997. return tp;
  1998. },
  1999. getPixelType: function(t) {
  2000. var tp;
  2001. switch (t) {
  2002. case 0: //char
  2003. tp = "S8";
  2004. break;
  2005. case 1: //byte
  2006. tp = "U8";
  2007. break;
  2008. case 2: //short
  2009. tp = "S16";
  2010. break;
  2011. case 3: //ushort
  2012. tp = "U16";
  2013. break;
  2014. case 4:
  2015. tp = "S32";
  2016. break;
  2017. case 5:
  2018. tp = "U32";
  2019. break;
  2020. case 6:
  2021. tp = "F32";
  2022. break;
  2023. case 7:
  2024. tp = "F64"; //not supported
  2025. break;
  2026. default:
  2027. tp = "F32";
  2028. }
  2029. return tp;
  2030. },
  2031. isValidPixelValue: function(t, val) {
  2032. if (val == null) {
  2033. return false;
  2034. }
  2035. var isValid;
  2036. switch (t) {
  2037. case 0: //char
  2038. isValid = val >= -128 && val <= 127;
  2039. break;
  2040. case 1: //byte (unsigned char)
  2041. isValid = val >= 0 && val <= 255;
  2042. break;
  2043. case 2: //short
  2044. isValid = val >= -32768 && val <= 32767;
  2045. break;
  2046. case 3: //ushort
  2047. isValid = val >= 0 && val <= 65536;
  2048. break;
  2049. case 4: //int 32
  2050. isValid = val >= -2147483648 && val <= 2147483647;
  2051. break;
  2052. case 5: //uinit 32
  2053. isValid = val >= 0 && val <= 4294967296;
  2054. break;
  2055. case 6:
  2056. isValid = val >= -3.4027999387901484e+38 && val <= 3.4027999387901484e+38;
  2057. break;
  2058. case 7:
  2059. isValid = val >= 5e-324 && val <= 1.7976931348623157e+308;
  2060. break;
  2061. default:
  2062. isValid = false;
  2063. }
  2064. return isValid;
  2065. },
  2066. getDataTypeSize: function(t) {
  2067. var s = 0;
  2068. switch (t) {
  2069. case 0: //ubyte
  2070. case 1: //byte
  2071. s = 1;
  2072. break;
  2073. case 2: //short
  2074. case 3: //ushort
  2075. s = 2;
  2076. break;
  2077. case 4:
  2078. case 5:
  2079. case 6:
  2080. s = 4;
  2081. break;
  2082. case 7:
  2083. s = 8;
  2084. break;
  2085. default:
  2086. s = t;
  2087. }
  2088. return s;
  2089. },
  2090. getDataTypeUsed: function(dt, tc) {
  2091. var t = dt;
  2092. switch (dt) {
  2093. case 2: //short
  2094. case 4: //long
  2095. t = dt - tc;
  2096. break;
  2097. case 3: //ushort
  2098. case 5: //ulong
  2099. t = dt - 2 * tc;
  2100. break;
  2101. case 6: //float
  2102. if (0 === tc) {
  2103. t = dt;
  2104. }
  2105. else if (1 === tc) {
  2106. t = 2;
  2107. }
  2108. else {
  2109. t = 1;//byte
  2110. }
  2111. break;
  2112. case 7: //double
  2113. if (0 === tc) {
  2114. t = dt;
  2115. }
  2116. else {
  2117. t = dt - 2 * tc + 1;
  2118. }
  2119. break;
  2120. default:
  2121. t = dt;
  2122. break;
  2123. }
  2124. return t;
  2125. },
  2126. getOnePixel: function(block, blockPtr, offsetType, view) {
  2127. var temp = 0;
  2128. switch (offsetType) {
  2129. case 0: //char
  2130. temp = view.getInt8(blockPtr);
  2131. break;
  2132. case 1: //byte
  2133. temp = view.getUint8(blockPtr);
  2134. break;
  2135. case 2:
  2136. temp = view.getInt16(blockPtr, true);
  2137. break;
  2138. case 3:
  2139. temp = view.getUint16(blockPtr, true);
  2140. break;
  2141. case 4:
  2142. temp = view.getInt32(blockPtr, true);
  2143. break;
  2144. case 5:
  2145. temp = view.getUInt32(blockPtr, true);
  2146. break;
  2147. case 6:
  2148. temp = view.getFloat32(blockPtr, true);
  2149. break;
  2150. case 7:
  2151. //temp = view.getFloat64(blockPtr, true);
  2152. //blockPtr += 8;
  2153. //lerc2 encoding doesnt handle float 64, force to float32???
  2154. temp = view.getFloat64(blockPtr, true);
  2155. break;
  2156. default:
  2157. throw ("the decoder does not understand this pixel type");
  2158. }
  2159. return temp;
  2160. }
  2161. };
  2162. /***************************************************
  2163. *private class for a tree node. Huffman code is in Lerc2Helpers
  2164. ****************************************************/
  2165. var TreeNode = function(val, left, right) {
  2166. this.val = val;
  2167. this.left = left;
  2168. this.right = right;
  2169. };
  2170. var Lerc2Decode = {
  2171. /*
  2172. * ********removed options compared to LERC1. We can bring some of them back if needed.
  2173. * removed pixel type. LERC2 is typed and doesn't require user to give pixel type
  2174. * changed encodedMaskData to maskData. LERC2 's js version make it faster to use maskData directly.
  2175. * removed returnMask. mask is used by LERC2 internally and is cost free. In case of user input mask, it's returned as well and has neglible cost.
  2176. * removed nodatavalue. Because LERC2 pixels are typed, nodatavalue will sacrify a useful value for many types (8bit, 16bit) etc,
  2177. * user has to be knowledgable enough about raster and their data to avoid usability issues. so nodata value is simply removed now.
  2178. * We can add it back later if their's a clear requirement.
  2179. * removed encodedMask. This option was not implemented in LercDecode. It can be done after decoding (less efficient)
  2180. * removed computeUsedBitDepths.
  2181. *
  2182. *
  2183. * response changes compared to LERC1
  2184. * 1. encodedMaskData is not available
  2185. * 2. noDataValue is optional (returns only if user's noDataValue is with in the valid data type range)
  2186. * 3. maskData is always available
  2187. */
  2188. /*****************
  2189. * public properties
  2190. ******************/
  2191. //HUFFMAN_LUT_BITS_MAX: 12, //use 2^12 lut, not configurable
  2192. /*****************
  2193. * public methods
  2194. *****************/
  2195. /**
  2196. * Decode a LERC2 byte stream and return an object containing the pixel data and optional metadata.
  2197. *
  2198. * @param {ArrayBuffer} input The LERC input byte stream
  2199. * @param {object} [options] options Decoding options
  2200. * @param {number} [options.inputOffset] The number of bytes to skip in the input byte stream. A valid LERC file is expected at that position
  2201. * @param {boolean} [options.returnFileInfo] If true, the return value will have a fileInfo property that contains metadata obtained from the LERC headers and the decoding process
  2202. */
  2203. decode: function(/*byte array*/ input, /*object*/ options) {
  2204. //currently there's a bug in the sparse array, so please do not set to false
  2205. options = options || {};
  2206. var noDataValue = options.noDataValue;
  2207. //initialize
  2208. var i = 0, data = {};
  2209. data.ptr = options.inputOffset || 0;
  2210. data.pixels = {};
  2211. // File header
  2212. if (!Lerc2Helpers.readHeaderInfo(input, data)) {
  2213. return;
  2214. }
  2215. var headerInfo = data.headerInfo;
  2216. var fileVersion = headerInfo.fileVersion;
  2217. var OutPixelTypeArray = Lerc2Helpers.getDataTypeArray(headerInfo.imageType);
  2218. // Mask Header
  2219. Lerc2Helpers.readMask(input, data);
  2220. if (headerInfo.numValidPixel !== headerInfo.width * headerInfo.height && !data.pixels.resultMask) {
  2221. data.pixels.resultMask = options.maskData;
  2222. }
  2223. var numPixels = headerInfo.width * headerInfo.height;
  2224. data.pixels.resultPixels = new OutPixelTypeArray(numPixels * headerInfo.numDims);
  2225. data.counter = {
  2226. onesweep: 0,
  2227. uncompressed: 0,
  2228. lut: 0,
  2229. bitstuffer: 0,
  2230. constant: 0,
  2231. constantoffset: 0
  2232. };
  2233. if (headerInfo.numValidPixel !== 0) {
  2234. //not tested
  2235. if (headerInfo.zMax === headerInfo.zMin) //constant surface
  2236. {
  2237. Lerc2Helpers.constructConstantSurface(data);
  2238. }
  2239. else if (fileVersion >= 4 && Lerc2Helpers.checkMinMaxRanges(input, data)) {
  2240. Lerc2Helpers.constructConstantSurface(data);
  2241. }
  2242. else {
  2243. var view = new DataView(input, data.ptr, 2);
  2244. var bReadDataOneSweep = view.getUint8(0);
  2245. data.ptr++;
  2246. if (bReadDataOneSweep) {
  2247. //console.debug("OneSweep");
  2248. Lerc2Helpers.readDataOneSweep(input, data, OutPixelTypeArray);
  2249. }
  2250. else {
  2251. //lerc2.1: //bitstuffing + lut
  2252. //lerc2.2: //bitstuffing + lut + huffman
  2253. //lerc2.3: new bitstuffer
  2254. if (fileVersion > 1 && headerInfo.imageType <= 1 && Math.abs(headerInfo.maxZError - 0.5) < 0.00001) {
  2255. //this is 2.x plus 8 bit (unsigned and signed) data, possiblity of Huffman
  2256. var flagHuffman = view.getUint8(1);
  2257. data.ptr++;
  2258. data.encodeMode = flagHuffman;
  2259. if (flagHuffman > 2 || (fileVersion < 4 && flagHuffman > 1)) {
  2260. throw "Invalid Huffman flag " + flagHuffman;
  2261. }
  2262. if (flagHuffman) {//1 - delta Huffman, 2 - Huffman
  2263. //console.log("Huffman");
  2264. Lerc2Helpers.readHuffman(input, data, OutPixelTypeArray);
  2265. }
  2266. else {
  2267. //console.log("Tiles");
  2268. Lerc2Helpers.readTiles(input, data, OutPixelTypeArray);
  2269. }
  2270. }
  2271. else { //lerc2.x non-8 bit data
  2272. //console.log("Tiles");
  2273. Lerc2Helpers.readTiles(input, data, OutPixelTypeArray);
  2274. }
  2275. }
  2276. }
  2277. }
  2278. data.eofOffset = data.ptr;
  2279. var diff;
  2280. if (options.inputOffset) {
  2281. diff = data.headerInfo.blobSize + options.inputOffset - data.ptr;
  2282. if (Math.abs(diff) >= 1) {
  2283. //console.debug("incorrect eof: dataptr " + data.ptr + " offset " + options.inputOffset + " blobsize " + data.headerInfo.blobSize + " diff: " + diff);
  2284. data.eofOffset = options.inputOffset + data.headerInfo.blobSize;
  2285. }
  2286. }
  2287. else {
  2288. diff = data.headerInfo.blobSize - data.ptr;
  2289. if (Math.abs(diff) >= 1) {
  2290. //console.debug("incorrect first band eof: dataptr " + data.ptr + " blobsize " + data.headerInfo.blobSize + " diff: " + diff);
  2291. data.eofOffset = data.headerInfo.blobSize;
  2292. }
  2293. }
  2294. var result = {
  2295. width: headerInfo.width,
  2296. height: headerInfo.height,
  2297. pixelData: data.pixels.resultPixels,
  2298. minValue: headerInfo.zMin,
  2299. maxValue: headerInfo.zMax,
  2300. validPixelCount: headerInfo.numValidPixel,
  2301. dimCount: headerInfo.numDims,
  2302. dimStats: {
  2303. minValues: headerInfo.minValues,
  2304. maxValues: headerInfo.maxValues
  2305. },
  2306. maskData: data.pixels.resultMask
  2307. //noDataValue: noDataValue
  2308. };
  2309. //we should remove this if there's no existing client
  2310. //optional noDataValue processing, it's user's responsiblity
  2311. if (data.pixels.resultMask && Lerc2Helpers.isValidPixelValue(headerInfo.imageType, noDataValue)) {
  2312. var mask = data.pixels.resultMask;
  2313. for (i = 0; i < numPixels; i++) {
  2314. if (!mask[i]) {
  2315. result.pixelData[i] = noDataValue;
  2316. }
  2317. }
  2318. result.noDataValue = noDataValue;
  2319. }
  2320. data.noDataValue = noDataValue;
  2321. if (options.returnFileInfo) {
  2322. result.fileInfo = Lerc2Helpers.formatFileInfo(data);
  2323. }
  2324. return result;
  2325. },
  2326. getBandCount: function(/*byte array*/ input) {
  2327. var count = 0;
  2328. var i = 0;
  2329. var temp = {};
  2330. temp.ptr = 0;
  2331. temp.pixels = {};
  2332. while (i < input.byteLength - 58) {
  2333. Lerc2Helpers.readHeaderInfo(input, temp);
  2334. i += temp.headerInfo.blobSize;
  2335. count++;
  2336. temp.ptr = i;
  2337. }
  2338. return count;
  2339. }
  2340. };
  2341. return Lerc2Decode;
  2342. })();
  2343. var isPlatformLittleEndian = (function() {
  2344. var a = new ArrayBuffer(4);
  2345. var b = new Uint8Array(a);
  2346. var c = new Uint32Array(a);
  2347. c[0] = 1;
  2348. return b[0] === 1;
  2349. })();
  2350. var Lerc = {
  2351. /************wrapper**********************************************/
  2352. /**
  2353. * A wrapper for decoding both LERC1 and LERC2 byte streams capable of handling multiband pixel blocks for various pixel types.
  2354. *
  2355. * @alias module:Lerc
  2356. * @param {ArrayBuffer} input The LERC input byte stream
  2357. * @param {object} [options] The decoding options below are optional.
  2358. * @param {number} [options.inputOffset] The number of bytes to skip in the input byte stream. A valid Lerc file is expected at that position.
  2359. * @param {string} [options.pixelType] (LERC1 only) Default value is F32. Valid pixel types for input are U8/S8/S16/U16/S32/U32/F32.
  2360. * @param {number} [options.noDataValue] (LERC1 only). It is recommended to use the returned mask instead of setting this value.
  2361. * @returns {{width, height, pixels, pixelType, mask, statistics}}
  2362. * @property {number} width Width of decoded image.
  2363. * @property {number} height Height of decoded image.
  2364. * @property {array} pixels [band1, band2, …] Each band is a typed array of width*height.
  2365. * @property {string} pixelType The type of pixels represented in the output.
  2366. * @property {mask} mask Typed array with a size of width*height, or null if all pixels are valid.
  2367. * @property {array} statistics [statistics_band1, statistics_band2, …] Each element is a statistics object representing min and max values
  2368. **/
  2369. decode: function(encodedData, options) {
  2370. if (!isPlatformLittleEndian) {
  2371. throw "Big endian system is not supported.";
  2372. }
  2373. options = options || {};
  2374. var inputOffset = options.inputOffset || 0;
  2375. var fileIdView = new Uint8Array(encodedData, inputOffset, 10);
  2376. var fileIdentifierString = String.fromCharCode.apply(null, fileIdView);
  2377. var lerc, majorVersion;
  2378. if (fileIdentifierString.trim() === "CntZImage") {
  2379. lerc = LercDecode;
  2380. majorVersion = 1;
  2381. }
  2382. else if (fileIdentifierString.substring(0, 5) === "Lerc2") {
  2383. lerc = Lerc2Decode;
  2384. majorVersion = 2;
  2385. }
  2386. else {
  2387. throw "Unexpected file identifier string: " + fileIdentifierString;
  2388. }
  2389. var iPlane = 0, eof = encodedData.byteLength - 10, encodedMaskData, bandMasks = [], bandMask, maskData;
  2390. var decodedPixelBlock = {
  2391. width: 0,
  2392. height: 0,
  2393. pixels: [],
  2394. pixelType: options.pixelType,
  2395. mask: null,
  2396. statistics: []
  2397. };
  2398. while (inputOffset < eof) {
  2399. var result = lerc.decode(encodedData, {
  2400. inputOffset: inputOffset,//for both lerc1 and lerc2
  2401. encodedMaskData: encodedMaskData,//lerc1 only
  2402. maskData: maskData,//lerc2 only
  2403. returnMask: iPlane === 0 ? true : false,//lerc1 only
  2404. returnEncodedMask: iPlane === 0 ? true : false,//lerc1 only
  2405. returnFileInfo: true,//for both lerc1 and lerc2
  2406. pixelType: options.pixelType || null,//lerc1 only
  2407. noDataValue: options.noDataValue || null//lerc1 only
  2408. });
  2409. inputOffset = result.fileInfo.eofOffset;
  2410. if (iPlane === 0) {
  2411. encodedMaskData = result.encodedMaskData;//lerc1
  2412. maskData = result.maskData;//lerc2
  2413. decodedPixelBlock.width = result.width;
  2414. decodedPixelBlock.height = result.height;
  2415. decodedPixelBlock.dimCount = result.dimCount || 1;
  2416. //decodedPixelBlock.dimStats = decodedPixelBlock.dimStats;
  2417. decodedPixelBlock.pixelType = result.pixelType || result.fileInfo.pixelType;
  2418. decodedPixelBlock.mask = result.maskData;
  2419. }
  2420. if (majorVersion >1 && result.fileInfo.mask && result.fileInfo.mask.numBytes > 0) {
  2421. bandMasks.push(result.maskData);
  2422. }
  2423. iPlane++;
  2424. decodedPixelBlock.pixels.push(result.pixelData);
  2425. decodedPixelBlock.statistics.push({
  2426. minValue: result.minValue,
  2427. maxValue: result.maxValue,
  2428. noDataValue: result.noDataValue,
  2429. dimStats: result.dimStats
  2430. });
  2431. }
  2432. var i, j, numPixels;
  2433. if (majorVersion > 1 && bandMasks.length > 1) {
  2434. numPixels = decodedPixelBlock.width * decodedPixelBlock.height;
  2435. decodedPixelBlock.bandMasks = bandMasks;
  2436. maskData = new Uint8Array(numPixels);
  2437. maskData.set(bandMasks[0]);
  2438. for (i = 1; i < bandMasks.length; i++) {
  2439. bandMask = bandMasks[i];
  2440. for (j = 0; j < numPixels; j++) {
  2441. maskData[j] = maskData[j] & bandMask[j];
  2442. }
  2443. }
  2444. decodedPixelBlock.maskData = maskData;
  2445. }
  2446. return decodedPixelBlock;
  2447. }
  2448. };
  2449. if (module.exports) {/* jshint ignore:line */
  2450. //commonJS module 1.0/1.1/1.1.1 systems, such as nodeJS
  2451. //http://wiki.commonjs.org/wiki/Modules
  2452. module.exports = Lerc;/* jshint ignore:line */
  2453. }
  2454. else {
  2455. //assign to this, most likely window
  2456. this.Lerc = Lerc;
  2457. }
  2458. })();
  2459. } (LercDecode));
  2460. var LercDecodeExports = LercDecode.exports;
  2461. var Lerc = /*@__PURE__*/Math$1.getDefaultExportFromCjs(LercDecodeExports);
  2462. function createVerticesFromHeightmap(parameters, transferableObjects) {
  2463. // LERC encoded buffers must be decoded, then we can process them like normal
  2464. if (parameters.encoding === HeightmapEncoding$1.LERC) {
  2465. let result;
  2466. try {
  2467. result = Lerc.decode(parameters.heightmap);
  2468. } catch (error) {
  2469. throw new RuntimeError.RuntimeError(error);
  2470. }
  2471. const lercStatistics = result.statistics[0];
  2472. if (lercStatistics.minValue === Number.MAX_VALUE) {
  2473. throw new RuntimeError.RuntimeError("Invalid tile data");
  2474. }
  2475. parameters.heightmap = result.pixels[0];
  2476. parameters.width = result.width;
  2477. parameters.height = result.height;
  2478. }
  2479. parameters.ellipsoid = Matrix3.Ellipsoid.clone(parameters.ellipsoid);
  2480. parameters.rectangle = Matrix2.Rectangle.clone(parameters.rectangle);
  2481. const statistics = HeightmapTessellator$1.computeVertices(parameters);
  2482. const vertices = statistics.vertices;
  2483. transferableObjects.push(vertices.buffer);
  2484. return {
  2485. vertices: vertices.buffer,
  2486. numberOfAttributes: statistics.encoding.stride,
  2487. minimumHeight: statistics.minimumHeight,
  2488. maximumHeight: statistics.maximumHeight,
  2489. gridWidth: parameters.width,
  2490. gridHeight: parameters.height,
  2491. boundingSphere3D: statistics.boundingSphere3D,
  2492. orientedBoundingBox: statistics.orientedBoundingBox,
  2493. occludeePointInScaledSpace: statistics.occludeePointInScaledSpace,
  2494. encoding: statistics.encoding,
  2495. westIndicesSouthToNorth: statistics.westIndicesSouthToNorth,
  2496. southIndicesEastToWest: statistics.southIndicesEastToWest,
  2497. eastIndicesNorthToSouth: statistics.eastIndicesNorthToSouth,
  2498. northIndicesWestToEast: statistics.northIndicesWestToEast,
  2499. };
  2500. }
  2501. var createVerticesFromHeightmap$1 = createTaskProcessorWorker(createVerticesFromHeightmap);
  2502. return createVerticesFromHeightmap$1;
  2503. }));