createVerticesFromHeightmap.js 106 KB

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