CCTGAlib.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. /****************************************************************************
  2. Copyright (c) 2010-2013 cocos2d-x.org
  3. http://www.cocos2d-x.org
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in
  11. all copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  18. THE SOFTWARE.
  19. ****************************************************************************/
  20. /**
  21. * @constant
  22. * @type Number
  23. */
  24. cc.TGA_OK = 0;
  25. /**
  26. * @constant
  27. * @type Number
  28. */
  29. cc.TGA_ERROR_FILE_OPEN = 1;
  30. /**
  31. * @constant
  32. * @type Number
  33. */
  34. cc.TGA_ERROR_READING_FILE = 2;
  35. /**
  36. * @constant
  37. * @type Number
  38. */
  39. cc.TGA_ERROR_INDEXED_COLOR = 3;
  40. /**
  41. * @constant
  42. * @type Number
  43. */
  44. cc.TGA_ERROR_MEMORY = 4;
  45. /**
  46. * @constant
  47. * @type Number
  48. */
  49. cc.TGA_ERROR_COMPRESSED_FILE = 5;
  50. /**
  51. * TGA format
  52. * @param {Number} status
  53. * @param {Number} type
  54. * @param {Number} pixelDepth
  55. * @param {Number} width map width
  56. * @param {Number} height map height
  57. * @param {Array} imageData raw data
  58. * @param {Number} flipped
  59. * @constructor
  60. */
  61. cc.ImageTGA = function (status, type, pixelDepth, width, height, imageData, flipped) {
  62. this.status = status || 0;
  63. this.type = type || 0;
  64. this.pixelDepth = pixelDepth || 0;
  65. this.width = width || 0;
  66. this.height = height || 0;
  67. this.imageData = imageData || [];
  68. this.flipped = flipped || 0;
  69. };
  70. /**
  71. * load the image header field from stream. We only keep those that matter!
  72. * @param {Array} buffer
  73. * @param {Number} bufSize
  74. * @param {cc.ImageTGA} psInfo
  75. * @return {Boolean}
  76. */
  77. cc.tgaLoadHeader = function (buffer, bufSize, psInfo) {
  78. var step = 2;
  79. if (step + 1 > bufSize)
  80. return false;
  81. var binaryReader = new cc.BinaryStreamReader(buffer);
  82. binaryReader.setOffset(step);
  83. psInfo.type = binaryReader.readByte();
  84. step += 10; // . step += sizeof(unsigned char) * 2; step += sizeof(signed short) * 4;
  85. if (step + 4 + 1 > bufSize)
  86. return false;
  87. binaryReader.setOffset(step);
  88. psInfo.width = binaryReader.readUnsignedShort();
  89. psInfo.height = binaryReader.readUnsignedInteger();
  90. psInfo.pixelDepth = binaryReader.readByte();
  91. step += 5; // . step += sizeof(unsigned char); step += sizeof(signed short) * 2;
  92. if (step + 1 > bufSize)
  93. return false;
  94. var garbage = binaryReader.readByte();
  95. psInfo.flipped = 0;
  96. if (garbage & 0x20)
  97. psInfo.flipped = 1;
  98. return true;
  99. };
  100. /**
  101. * loads the image pixels. You shouldn't call this function directly
  102. * @param {Array} buffer
  103. * @param {Number} bufSize
  104. * @param {cc.ImageTGA} psInfo
  105. * @return {Boolean}
  106. */
  107. cc.tgaLoadImageData = function (buffer, bufSize, psInfo) {
  108. var mode, total, i, aux;
  109. var step = 18; // .size_t step = (sizeof(unsigned char) + sizeof(signed short)) * 6;
  110. // mode equal the number of components for each pixel
  111. mode = 0 | (psInfo.pixelDepth / 2);
  112. // total is the number of unsigned chars we'll have to read
  113. total = psInfo.height * psInfo.width * mode;
  114. if (step + total > bufSize)
  115. return false;
  116. psInfo.imageData = cc.__getSubArray(buffer, step, step + total);
  117. // mode=3 or 4 implies that the image is RGB(A). However TGA
  118. // stores it as BGR(A) so we'll have to swap R and B.
  119. if (mode >= 3) {
  120. for (i = 0; i < total; i += mode) {
  121. aux = psInfo.imageData[i];
  122. psInfo.imageData[i] = psInfo.imageData[i + 2];
  123. psInfo.imageData[i + 2] = aux;
  124. }
  125. }
  126. return true;
  127. };
  128. /**
  129. * this is the function to call when we want to load an image
  130. * @param filename
  131. * @return {cc.ImageTGA}
  132. */
  133. cc.tgaLoad = function (filename) {
  134. var buffer = cc.FileUtils.getInstance().getFileData(filename, "rb");
  135. var size = buffer.length;
  136. if (buffer == null)
  137. return null;
  138. var info = new cc.ImageTGA();
  139. // get the file header info
  140. if (!cc.tgaLoadHeader(buffer, size, info)) {
  141. info.status = cc.TGA_ERROR_MEMORY;
  142. return info;
  143. }
  144. // check if the image is color indexed
  145. if (info.type === 1) {
  146. info.status = cc.TGA_ERROR_INDEXED_COLOR;
  147. return info;
  148. }
  149. // check for other types (compressed images)
  150. if ((info.type != 2) && (info.type != 3) && (info.type != 10)) {
  151. info.status = cc.TGA_ERROR_COMPRESSED_FILE;
  152. return info;
  153. }
  154. var bLoadImage = false;
  155. // finally load the image pixels
  156. if (info.type == 10)
  157. bLoadImage = cc.tgaLoadRLEImageData(buffer, size, info);
  158. else
  159. bLoadImage = cc.tgaLoadImageData(buffer, size, info);
  160. // check for errors when reading the pixels
  161. if (!bLoadImage) {
  162. info.status = cc.TGA_ERROR_READING_FILE;
  163. return info;
  164. }
  165. info.status = cc.TGA_OK;
  166. if (info.flipped) {
  167. cc.tgaFlipImage(info);
  168. if (info.flipped)
  169. info.status = cc.TGA_ERROR_MEMORY;
  170. }
  171. buffer = null;
  172. return info;
  173. };
  174. /**
  175. * converts RGB to grayscale
  176. * @param {cc.ImageTGA} psInfo
  177. */
  178. cc.tgaRGBtogreyscale = function (psInfo) {
  179. var i, j;
  180. // if the image is already grayscale do nothing
  181. if (psInfo.pixelDepth === 8)
  182. return;
  183. // compute the number of actual components
  184. var mode = psInfo.pixelDepth / 8;
  185. // allocate an array for the new image data
  186. var newImageData = new Uint8Array(psInfo.height * psInfo.width);
  187. if (newImageData === null)
  188. return;
  189. // convert pixels: grayscale = o.30 * R + 0.59 * G + 0.11 * B
  190. for (i = 0, j = 0; j < psInfo.width * psInfo.height; i += mode, j++)
  191. newImageData[j] = (0.30 * psInfo.imageData[i] + 0.59 * psInfo.imageData[i + 1] + 0.11 * psInfo.imageData[i + 2]);
  192. // reassign pixelDepth and type according to the new image type
  193. psInfo.pixelDepth = 8;
  194. psInfo.type = 3;
  195. // reassigning imageData to the new array.
  196. psInfo.imageData = newImageData;
  197. };
  198. /**
  199. * releases the memory used for the image
  200. * @param {cc.ImageTGA} psInfo
  201. */
  202. cc.tgaDestroy = function (psInfo) {
  203. if (!psInfo)
  204. return;
  205. psInfo.imageData = null;
  206. psInfo = null;
  207. };
  208. cc.tgaLoadRLEImageData = function (buffer, bufSize, psInfo) {
  209. var mode, total, i, index = 0 , skip = 0, flag = 0;
  210. var aux = [], runlength = 0;
  211. var step = 18; // . size_t step = (sizeof(unsigned char) + sizeof(signed short)) * 6;
  212. // mode equal the number of components for each pixel
  213. mode = psInfo.pixelDepth / 8;
  214. // total is the number of unsigned chars we'll have to read
  215. total = psInfo.height * psInfo.width;
  216. for (i = 0; i < total; i++) {
  217. // if we have a run length pending, run it
  218. if (runlength != 0) {
  219. // we do, update the run length count
  220. runlength--;
  221. skip = (flag != 0);
  222. } else {
  223. // otherwise, read in the run length token
  224. if (step + 1 > bufSize)
  225. break;
  226. runlength = buffer[step];
  227. step += 1;
  228. // see if it's a RLE encoded sequence
  229. flag = runlength & 0x80;
  230. if (flag)
  231. runlength -= 128;
  232. skip = 0;
  233. }
  234. // do we need to skip reading this pixel?
  235. if (!skip) {
  236. // no, read in the pixel data
  237. if (step + mode > bufSize)
  238. break;
  239. aux = cc.__getSubArray(buffer, step, step + mode);
  240. step += mode;
  241. // mode=3 or 4 implies that the image is RGB(A). However TGA
  242. // stores it as BGR(A) so we'll have to swap R and B.
  243. if (mode >= 3) {
  244. var tmp = aux[0];
  245. aux[0] = aux[2];
  246. aux[2] = tmp;
  247. }
  248. }
  249. // add the pixel to our image
  250. for (var j = 0; j < mode; j++)
  251. psInfo.imageData[index + j] = aux[j];
  252. index += mode;
  253. }
  254. return true;
  255. };
  256. cc.tgaFlipImage = function (psInfo) {
  257. // mode equal the number of components for each pixel
  258. var mode = psInfo.pixelDepth / 8;
  259. var rowbytes = psInfo.width * mode;
  260. for (var y = 0; y < (psInfo.height / 2); y++) {
  261. var row = cc.__getSubArray(psInfo.imageData, y * rowbytes, y * rowbytes + rowbytes);
  262. cc.__setDataToArray(cc.__getSubArray(psInfo.imageData, (psInfo.height - (y + 1)) * rowbytes, rowbytes), psInfo.imageData, y * rowbytes);
  263. cc.__setDataToArray(row, psInfo.imageData, (psInfo.height - (y + 1)) * rowbytes);
  264. }
  265. psInfo.flipped = 0;
  266. };
  267. cc.__getSubArray = function (array, start, end) {
  268. if (array instanceof Array)
  269. return array.slice(start, end);
  270. else
  271. return array.subarray(start, end);
  272. };
  273. cc.__setDataToArray = function (sourceData, destArray, startIndex) {
  274. for (var i = 0; i < sourceData.length; i++)
  275. destArray[startIndex + i] = sourceData[i];
  276. };
  277. cc.BinaryStreamReader = cc.Class.extend({
  278. _binaryData:null,
  279. _offset:0,
  280. ctor:function (binaryData) {
  281. this._binaryData = binaryData;
  282. },
  283. setBinaryData:function (binaryData) {
  284. this._binaryData = binaryData;
  285. this._offset = 0;
  286. },
  287. getBinaryData:function () {
  288. return this._binaryData;
  289. },
  290. _checkSize:function (neededBits) {
  291. if (!(this._offset + Math.ceil(neededBits / 8) < this._data.length))
  292. throw new Error("Index out of bound");
  293. },
  294. _decodeFloat:function (precisionBits, exponentBits) {
  295. var length = precisionBits + exponentBits + 1;
  296. var size = length >> 3;
  297. this._checkSize(length);
  298. var bias = Math.pow(2, exponentBits - 1) - 1;
  299. var signal = this._readBits(precisionBits + exponentBits, 1, size);
  300. var exponent = this._readBits(precisionBits, exponentBits, size);
  301. var significand = 0;
  302. var divisor = 2;
  303. var curByte = 0; //length + (-precisionBits >> 3) - 1;
  304. do {
  305. var byteValue = this._readByte(++curByte, size);
  306. var startBit = precisionBits % 8 || 8;
  307. var mask = 1 << startBit;
  308. while (mask >>= 1) {
  309. if (byteValue & mask)
  310. significand += 1 / divisor;
  311. divisor *= 2;
  312. }
  313. } while (precisionBits -= startBit);
  314. this._offset += size;
  315. return exponent == (bias << 1) + 1 ? significand ? NaN : signal ? -Infinity : +Infinity
  316. : (1 + signal * -2) * (exponent || significand ? !exponent ? Math.pow(2, -bias + 1) * significand
  317. : Math.pow(2, exponent - bias) * (1 + significand) : 0);
  318. },
  319. _readByte:function (i, size) {
  320. return this._data[this._offset + size - i - 1];
  321. },
  322. _decodeInt:function (bits, signed) {
  323. var x = this._readBits(0, bits, bits / 8), max = Math.pow(2, bits);
  324. var result = signed && x >= max / 2 ? x - max : x;
  325. this._offset += bits / 8;
  326. return result;
  327. },
  328. _shl:function (a, b) {
  329. for (++b; --b; a = ((a %= 0x7fffffff + 1) & 0x40000000) == 0x40000000 ? a * 2 : (a - 0x40000000) * 2 + 0x7fffffff + 1){};
  330. return a;
  331. },
  332. _readBits:function (start, length, size) {
  333. var offsetLeft = (start + length) % 8;
  334. var offsetRight = start % 8;
  335. var curByte = size - (start >> 3) - 1;
  336. var lastByte = size + (-(start + length) >> 3);
  337. var diff = curByte - lastByte;
  338. var sum = (this._readByte(curByte, size) >> offsetRight) & ((1 << (diff ? 8 - offsetRight : length)) - 1);
  339. if (diff && offsetLeft)
  340. sum += (this._readByte(lastByte++, size) & ((1 << offsetLeft) - 1)) << (diff-- << 3) - offsetRight;
  341. while (diff)
  342. sum += this._shl(this._readByte(lastByte++, size), (diff-- << 3) - offsetRight);
  343. return sum;
  344. },
  345. readInteger:function () {
  346. return this._decodeInt(32, true);
  347. },
  348. readUnsignedInteger:function () {
  349. return this._decodeInt(32, false);
  350. },
  351. readSingle:function () {
  352. return this._decodeFloat(23, 8);
  353. },
  354. readShort:function () {
  355. return this._decodeInt(16, true);
  356. },
  357. readUnsignedShort:function () {
  358. return this._decodeInt(16, false);
  359. },
  360. readByte:function () {
  361. var readByte = this._data[this._offset];
  362. this._offset += 1;
  363. return readByte;
  364. },
  365. readData:function (start, end) {
  366. if (this._binaryData instanceof Array) {
  367. return this._binaryData.slice(start, end);
  368. } else {
  369. //typed array
  370. return this._binaryData.subarray(start, end);
  371. }
  372. },
  373. setOffset:function (offset) {
  374. this._offset = offset;
  375. },
  376. getOffset:function () {
  377. return this._offset;
  378. }
  379. });