createVerticesFromHeightmap.js 111 KB

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