spritesheet.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. /*!
  2. * @pixi/spritesheet - v6.5.10
  3. * Compiled Thu, 06 Jul 2023 15:25:11 UTC
  4. *
  5. * @pixi/spritesheet is licensed under the MIT License.
  6. * http://www.opensource.org/licenses/mit-license
  7. */
  8. 'use strict';
  9. Object.defineProperty(exports, '__esModule', { value: true });
  10. var math = require('@pixi/math');
  11. var core = require('@pixi/core');
  12. var utils = require('@pixi/utils');
  13. var loaders = require('@pixi/loaders');
  14. /**
  15. * Utility class for maintaining reference to a collection
  16. * of Textures on a single Spritesheet.
  17. *
  18. * To access a sprite sheet from your code you may pass its JSON data file to Pixi's loader:
  19. *
  20. * ```js
  21. * PIXI.Loader.shared.add("images/spritesheet.json").load(setup);
  22. *
  23. * function setup() {
  24. * let sheet = PIXI.Loader.shared.resources["images/spritesheet.json"].spritesheet;
  25. * ...
  26. * }
  27. * ```
  28. *
  29. * Alternately, you may circumvent the loader by instantiating the Spritesheet directly:
  30. * ```js
  31. * const sheet = new PIXI.Spritesheet(texture, spritesheetData);
  32. * await sheet.parse();
  33. * console.log('Spritesheet ready to use!');
  34. * ```
  35. *
  36. * With the `sheet.textures` you can create Sprite objects,`sheet.animations` can be used to create an AnimatedSprite.
  37. *
  38. * Sprite sheets can be packed using tools like {@link https://codeandweb.com/texturepacker|TexturePacker},
  39. * {@link https://renderhjs.net/shoebox/|Shoebox} or {@link https://github.com/krzysztof-o/spritesheet.js|Spritesheet.js}.
  40. * Default anchor points (see {@link PIXI.Texture#defaultAnchor}) and grouping of animation sprites are currently only
  41. * supported by TexturePacker.
  42. * @memberof PIXI
  43. */
  44. var Spritesheet = /** @class */ (function () {
  45. /**
  46. * @param texture - Reference to the source BaseTexture object.
  47. * @param {object} data - Spritesheet image data.
  48. * @param resolutionFilename - The filename to consider when determining
  49. * the resolution of the spritesheet. If not provided, the imageUrl will
  50. * be used on the BaseTexture.
  51. */
  52. function Spritesheet(texture, data, resolutionFilename) {
  53. if (resolutionFilename === void 0) { resolutionFilename = null; }
  54. /** For multi-packed spritesheets, this contains a reference to all the other spritesheets it depends on. */
  55. this.linkedSheets = [];
  56. this._texture = texture instanceof core.Texture ? texture : null;
  57. this.baseTexture = texture instanceof core.BaseTexture ? texture : this._texture.baseTexture;
  58. this.textures = {};
  59. this.animations = {};
  60. this.data = data;
  61. var resource = this.baseTexture.resource;
  62. this.resolution = this._updateResolution(resolutionFilename || (resource ? resource.url : null));
  63. this._frames = this.data.frames;
  64. this._frameKeys = Object.keys(this._frames);
  65. this._batchIndex = 0;
  66. this._callback = null;
  67. }
  68. /**
  69. * Generate the resolution from the filename or fallback
  70. * to the meta.scale field of the JSON data.
  71. * @param resolutionFilename - The filename to use for resolving
  72. * the default resolution.
  73. * @returns Resolution to use for spritesheet.
  74. */
  75. Spritesheet.prototype._updateResolution = function (resolutionFilename) {
  76. if (resolutionFilename === void 0) { resolutionFilename = null; }
  77. var scale = this.data.meta.scale;
  78. // Use a defaultValue of `null` to check if a url-based resolution is set
  79. var resolution = utils.getResolutionOfUrl(resolutionFilename, null);
  80. // No resolution found via URL
  81. if (resolution === null) {
  82. // Use the scale value or default to 1
  83. resolution = scale !== undefined ? parseFloat(scale) : 1;
  84. }
  85. // For non-1 resolutions, update baseTexture
  86. if (resolution !== 1) {
  87. this.baseTexture.setResolution(resolution);
  88. }
  89. return resolution;
  90. };
  91. /** @ignore */
  92. Spritesheet.prototype.parse = function (callback) {
  93. var _this = this;
  94. if (callback) {
  95. utils.deprecation('6.5.0', 'Spritesheet.parse callback is deprecated, use the return Promise instead.');
  96. }
  97. return new Promise(function (resolve) {
  98. _this._callback = function (textures) {
  99. callback === null || callback === void 0 ? void 0 : callback(textures);
  100. resolve(textures);
  101. };
  102. _this._batchIndex = 0;
  103. if (_this._frameKeys.length <= Spritesheet.BATCH_SIZE) {
  104. _this._processFrames(0);
  105. _this._processAnimations();
  106. _this._parseComplete();
  107. }
  108. else {
  109. _this._nextBatch();
  110. }
  111. });
  112. };
  113. /**
  114. * Process a batch of frames
  115. * @param initialFrameIndex - The index of frame to start.
  116. */
  117. Spritesheet.prototype._processFrames = function (initialFrameIndex) {
  118. var frameIndex = initialFrameIndex;
  119. var maxFrames = Spritesheet.BATCH_SIZE;
  120. while (frameIndex - initialFrameIndex < maxFrames && frameIndex < this._frameKeys.length) {
  121. var i = this._frameKeys[frameIndex];
  122. var data = this._frames[i];
  123. var rect = data.frame;
  124. if (rect) {
  125. var frame = null;
  126. var trim = null;
  127. var sourceSize = data.trimmed !== false && data.sourceSize
  128. ? data.sourceSize : data.frame;
  129. var orig = new math.Rectangle(0, 0, Math.floor(sourceSize.w) / this.resolution, Math.floor(sourceSize.h) / this.resolution);
  130. if (data.rotated) {
  131. frame = new math.Rectangle(Math.floor(rect.x) / this.resolution, Math.floor(rect.y) / this.resolution, Math.floor(rect.h) / this.resolution, Math.floor(rect.w) / this.resolution);
  132. }
  133. else {
  134. frame = new math.Rectangle(Math.floor(rect.x) / this.resolution, Math.floor(rect.y) / this.resolution, Math.floor(rect.w) / this.resolution, Math.floor(rect.h) / this.resolution);
  135. }
  136. // Check to see if the sprite is trimmed
  137. if (data.trimmed !== false && data.spriteSourceSize) {
  138. trim = new math.Rectangle(Math.floor(data.spriteSourceSize.x) / this.resolution, Math.floor(data.spriteSourceSize.y) / this.resolution, Math.floor(rect.w) / this.resolution, Math.floor(rect.h) / this.resolution);
  139. }
  140. this.textures[i] = new core.Texture(this.baseTexture, frame, orig, trim, data.rotated ? 2 : 0, data.anchor);
  141. // lets also add the frame to pixi's global cache for 'from' and 'fromLoader' functions
  142. core.Texture.addToCache(this.textures[i], i);
  143. }
  144. frameIndex++;
  145. }
  146. };
  147. /** Parse animations config. */
  148. Spritesheet.prototype._processAnimations = function () {
  149. var animations = this.data.animations || {};
  150. for (var animName in animations) {
  151. this.animations[animName] = [];
  152. for (var i = 0; i < animations[animName].length; i++) {
  153. var frameName = animations[animName][i];
  154. this.animations[animName].push(this.textures[frameName]);
  155. }
  156. }
  157. };
  158. /** The parse has completed. */
  159. Spritesheet.prototype._parseComplete = function () {
  160. var callback = this._callback;
  161. this._callback = null;
  162. this._batchIndex = 0;
  163. callback.call(this, this.textures);
  164. };
  165. /** Begin the next batch of textures. */
  166. Spritesheet.prototype._nextBatch = function () {
  167. var _this = this;
  168. this._processFrames(this._batchIndex * Spritesheet.BATCH_SIZE);
  169. this._batchIndex++;
  170. setTimeout(function () {
  171. if (_this._batchIndex * Spritesheet.BATCH_SIZE < _this._frameKeys.length) {
  172. _this._nextBatch();
  173. }
  174. else {
  175. _this._processAnimations();
  176. _this._parseComplete();
  177. }
  178. }, 0);
  179. };
  180. /**
  181. * Destroy Spritesheet and don't use after this.
  182. * @param {boolean} [destroyBase=false] - Whether to destroy the base texture as well
  183. */
  184. Spritesheet.prototype.destroy = function (destroyBase) {
  185. var _a;
  186. if (destroyBase === void 0) { destroyBase = false; }
  187. for (var i in this.textures) {
  188. this.textures[i].destroy();
  189. }
  190. this._frames = null;
  191. this._frameKeys = null;
  192. this.data = null;
  193. this.textures = null;
  194. if (destroyBase) {
  195. (_a = this._texture) === null || _a === void 0 ? void 0 : _a.destroy();
  196. this.baseTexture.destroy();
  197. }
  198. this._texture = null;
  199. this.baseTexture = null;
  200. this.linkedSheets = [];
  201. };
  202. /** The maximum number of Textures to build per process. */
  203. Spritesheet.BATCH_SIZE = 1000;
  204. return Spritesheet;
  205. }());
  206. /**
  207. * Reference to Spritesheet object created.
  208. * @member {PIXI.Spritesheet} spritesheet
  209. * @memberof PIXI.LoaderResource
  210. * @instance
  211. */
  212. /**
  213. * Dictionary of textures from Spritesheet.
  214. * @member {Object<string, PIXI.Texture>} textures
  215. * @memberof PIXI.LoaderResource
  216. * @instance
  217. */
  218. /**
  219. * {@link PIXI.Loader} middleware for loading texture atlases that have been created with
  220. * TexturePacker or similar JSON-based spritesheet.
  221. *
  222. * This middleware automatically generates Texture resources.
  223. *
  224. * If you're using Webpack or other bundlers and plan on bundling the atlas' JSON,
  225. * use the {@link PIXI.Spritesheet} class to directly parse the JSON.
  226. *
  227. * The Loader's image Resource name is automatically appended with `"_image"`.
  228. * If a Resource with this name is already loaded, the Loader will skip parsing the
  229. * Spritesheet. The code below will generate an internal Loader Resource called `"myatlas_image"`.
  230. * @example
  231. * loader.add('myatlas', 'path/to/myatlas.json');
  232. * loader.load(() => {
  233. * loader.resources.myatlas; // atlas JSON resource
  234. * loader.resources.myatlas_image; // atlas Image resource
  235. * });
  236. * @memberof PIXI
  237. */
  238. var SpritesheetLoader = /** @class */ (function () {
  239. function SpritesheetLoader() {
  240. }
  241. /**
  242. * Called after a resource is loaded.
  243. * @see PIXI.Loader.loaderMiddleware
  244. * @param resource
  245. * @param next
  246. */
  247. SpritesheetLoader.use = function (resource, next) {
  248. var _a, _b;
  249. // because this is middleware, it execute in loader context. `this` = loader
  250. var loader = this;
  251. var imageResourceName = resource.name + "_image";
  252. // skip if no data, its not json, it isn't spritesheet data, or the image resource already exists
  253. if (!resource.data
  254. || resource.type !== loaders.LoaderResource.TYPE.JSON
  255. || !resource.data.frames
  256. || loader.resources[imageResourceName]) {
  257. next();
  258. return;
  259. }
  260. // Check and add the multi atlas
  261. // Heavily influenced and based on https://github.com/rocket-ua/pixi-tps-loader/blob/master/src/ResourceLoader.js
  262. // eslint-disable-next-line camelcase
  263. var multiPacks = (_b = (_a = resource.data) === null || _a === void 0 ? void 0 : _a.meta) === null || _b === void 0 ? void 0 : _b.related_multi_packs;
  264. if (Array.isArray(multiPacks)) {
  265. var _loop_1 = function (item) {
  266. if (typeof item !== 'string') {
  267. return "continue";
  268. }
  269. var itemName = item.replace('.json', '');
  270. var itemUrl = utils.url.resolve(resource.url.replace(loader.baseUrl, ''), item);
  271. // Check if the file wasn't already added as multipacks are redundant
  272. if (loader.resources[itemName]
  273. || Object.values(loader.resources).some(function (r) { return utils.url.format(utils.url.parse(r.url)) === itemUrl; })) {
  274. return "continue";
  275. }
  276. var options = {
  277. crossOrigin: resource.crossOrigin,
  278. loadType: loaders.LoaderResource.LOAD_TYPE.XHR,
  279. xhrType: loaders.LoaderResource.XHR_RESPONSE_TYPE.JSON,
  280. parentResource: resource,
  281. metadata: resource.metadata
  282. };
  283. loader.add(itemName, itemUrl, options);
  284. };
  285. for (var _i = 0, multiPacks_1 = multiPacks; _i < multiPacks_1.length; _i++) {
  286. var item = multiPacks_1[_i];
  287. _loop_1(item);
  288. }
  289. }
  290. var loadOptions = {
  291. crossOrigin: resource.crossOrigin,
  292. metadata: resource.metadata.imageMetadata,
  293. parentResource: resource,
  294. };
  295. var resourcePath = SpritesheetLoader.getResourcePath(resource, loader.baseUrl);
  296. // load the image for this sheet
  297. loader.add(imageResourceName, resourcePath, loadOptions, function onImageLoad(res) {
  298. if (res.error) {
  299. next(res.error);
  300. return;
  301. }
  302. var spritesheet = new Spritesheet(res.texture, resource.data, resource.url);
  303. spritesheet.parse().then(function () {
  304. resource.spritesheet = spritesheet;
  305. resource.textures = spritesheet.textures;
  306. next();
  307. });
  308. });
  309. };
  310. /**
  311. * Get the spritesheets root path
  312. * @param resource - Resource to check path
  313. * @param baseUrl - Base root url
  314. */
  315. SpritesheetLoader.getResourcePath = function (resource, baseUrl) {
  316. // Prepend url path unless the resource image is a data url
  317. if (resource.isDataUrl) {
  318. return resource.data.meta.image;
  319. }
  320. return utils.url.resolve(resource.url.replace(baseUrl, ''), resource.data.meta.image);
  321. };
  322. /** @ignore */
  323. SpritesheetLoader.extension = core.ExtensionType.Loader;
  324. return SpritesheetLoader;
  325. }());
  326. exports.Spritesheet = Spritesheet;
  327. exports.SpritesheetLoader = SpritesheetLoader;
  328. //# sourceMappingURL=spritesheet.js.map