UNPKG

14.2 kBJavaScriptView Raw
1"use strict";
2var math = require("@pixi/math"), settings = require("@pixi/settings"), utils = require("@pixi/utils"), BaseTexture = require("./BaseTexture.js"), ImageResource = require("./resources/ImageResource.js"), TextureUvs = require("./TextureUvs.js");
3const DEFAULT_UVS = new TextureUvs.TextureUvs();
4function removeAllHandlers(tex) {
5 tex.destroy = function() {
6 }, tex.on = function() {
7 }, tex.once = function() {
8 }, tex.emit = function() {
9 };
10}
11class Texture extends utils.EventEmitter {
12 /**
13 * @param baseTexture - The base texture source to create the texture from
14 * @param frame - The rectangle frame of the texture to show
15 * @param orig - The area of original texture
16 * @param trim - Trimmed rectangle of original texture
17 * @param rotate - indicates how the texture was rotated by texture packer. See {@link PIXI.groupD8}
18 * @param anchor - Default anchor point used for sprite placement / rotation
19 * @param borders - Default borders used for 9-slice scaling. See {@link PIXI.NineSlicePlane}
20 */
21 constructor(baseTexture, frame, orig, trim, rotate, anchor, borders) {
22 if (super(), this.noFrame = !1, frame || (this.noFrame = !0, frame = new math.Rectangle(0, 0, 1, 1)), baseTexture instanceof Texture && (baseTexture = baseTexture.baseTexture), this.baseTexture = baseTexture, this._frame = frame, this.trim = trim, this.valid = !1, this.destroyed = !1, this._uvs = DEFAULT_UVS, this.uvMatrix = null, this.orig = orig || frame, this._rotate = Number(rotate || 0), rotate === !0)
23 this._rotate = 2;
24 else if (this._rotate % 2 !== 0)
25 throw new Error("attempt to use diamond-shaped UVs. If you are sure, set rotation manually");
26 this.defaultAnchor = anchor ? new math.Point(anchor.x, anchor.y) : new math.Point(0, 0), this.defaultBorders = borders, this._updateID = 0, this.textureCacheIds = [], baseTexture.valid ? this.noFrame ? baseTexture.valid && this.onBaseTextureUpdated(baseTexture) : this.frame = frame : baseTexture.once("loaded", this.onBaseTextureUpdated, this), this.noFrame && baseTexture.on("update", this.onBaseTextureUpdated, this);
27 }
28 /**
29 * Updates this texture on the gpu.
30 *
31 * Calls the TextureResource update.
32 *
33 * If you adjusted `frame` manually, please call `updateUvs()` instead.
34 */
35 update() {
36 this.baseTexture.resource && this.baseTexture.resource.update();
37 }
38 /**
39 * Called when the base texture is updated
40 * @protected
41 * @param baseTexture - The base texture.
42 */
43 onBaseTextureUpdated(baseTexture) {
44 if (this.noFrame) {
45 if (!this.baseTexture.valid)
46 return;
47 this._frame.width = baseTexture.width, this._frame.height = baseTexture.height, this.valid = !0, this.updateUvs();
48 } else
49 this.frame = this._frame;
50 this.emit("update", this);
51 }
52 /**
53 * Destroys this texture
54 * @param [destroyBase=false] - Whether to destroy the base texture as well
55 * @fires PIXI.Texture#destroyed
56 */
57 destroy(destroyBase) {
58 if (this.baseTexture) {
59 if (destroyBase) {
60 const { resource } = this.baseTexture;
61 resource?.url && utils.TextureCache[resource.url] && Texture.removeFromCache(resource.url), this.baseTexture.destroy();
62 }
63 this.baseTexture.off("loaded", this.onBaseTextureUpdated, this), this.baseTexture.off("update", this.onBaseTextureUpdated, this), this.baseTexture = null;
64 }
65 this._frame = null, this._uvs = null, this.trim = null, this.orig = null, this.valid = !1, Texture.removeFromCache(this), this.textureCacheIds = null, this.destroyed = !0, this.emit("destroyed", this), this.removeAllListeners();
66 }
67 /**
68 * Creates a new texture object that acts the same as this one.
69 * @returns - The new texture
70 */
71 clone() {
72 const clonedFrame = this._frame.clone(), clonedOrig = this._frame === this.orig ? clonedFrame : this.orig.clone(), clonedTexture = new Texture(
73 this.baseTexture,
74 !this.noFrame && clonedFrame,
75 clonedOrig,
76 this.trim?.clone(),
77 this.rotate,
78 this.defaultAnchor,
79 this.defaultBorders
80 );
81 return this.noFrame && (clonedTexture._frame = clonedFrame), clonedTexture;
82 }
83 /**
84 * Updates the internal WebGL UV cache. Use it after you change `frame` or `trim` of the texture.
85 * Call it after changing the frame
86 */
87 updateUvs() {
88 this._uvs === DEFAULT_UVS && (this._uvs = new TextureUvs.TextureUvs()), this._uvs.set(this._frame, this.baseTexture, this.rotate), this._updateID++;
89 }
90 /**
91 * Helper function that creates a new Texture based on the source you provide.
92 * The source can be - frame id, image url, video url, canvas element, video element, base texture
93 * @param {string|PIXI.BaseTexture|HTMLImageElement|HTMLVideoElement|ImageBitmap|PIXI.ICanvas} source -
94 * Source or array of sources to create texture from
95 * @param options - See {@link PIXI.BaseTexture}'s constructor for options.
96 * @param {string} [options.pixiIdPrefix=pixiid] - If a source has no id, this is the prefix of the generated id
97 * @param {boolean} [strict] - Enforce strict-mode, see {@link PIXI.settings.STRICT_TEXTURE_CACHE}.
98 * @returns {PIXI.Texture} The newly created texture
99 */
100 static from(source, options = {}, strict = settings.settings.STRICT_TEXTURE_CACHE) {
101 const isFrame = typeof source == "string";
102 let cacheId = null;
103 if (isFrame)
104 cacheId = source;
105 else if (source instanceof BaseTexture.BaseTexture) {
106 if (!source.cacheId) {
107 const prefix = options?.pixiIdPrefix || "pixiid";
108 source.cacheId = `${prefix}-${utils.uid()}`, BaseTexture.BaseTexture.addToCache(source, source.cacheId);
109 }
110 cacheId = source.cacheId;
111 } else {
112 if (!source._pixiId) {
113 const prefix = options?.pixiIdPrefix || "pixiid";
114 source._pixiId = `${prefix}_${utils.uid()}`;
115 }
116 cacheId = source._pixiId;
117 }
118 let texture = utils.TextureCache[cacheId];
119 if (isFrame && strict && !texture)
120 throw new Error(`The cacheId "${cacheId}" does not exist in TextureCache.`);
121 return !texture && !(source instanceof BaseTexture.BaseTexture) ? (options.resolution || (options.resolution = utils.getResolutionOfUrl(source)), texture = new Texture(new BaseTexture.BaseTexture(source, options)), texture.baseTexture.cacheId = cacheId, BaseTexture.BaseTexture.addToCache(texture.baseTexture, cacheId), Texture.addToCache(texture, cacheId)) : !texture && source instanceof BaseTexture.BaseTexture && (texture = new Texture(source), Texture.addToCache(texture, cacheId)), texture;
122 }
123 /**
124 * Useful for loading textures via URLs. Use instead of `Texture.from` because
125 * it does a better job of handling failed URLs more effectively. This also ignores
126 * `PIXI.settings.STRICT_TEXTURE_CACHE`. Works for Videos, SVGs, Images.
127 * @param url - The remote URL or array of URLs to load.
128 * @param options - Optional options to include
129 * @returns - A Promise that resolves to a Texture.
130 */
131 static fromURL(url, options) {
132 const resourceOptions = Object.assign({ autoLoad: !1 }, options?.resourceOptions), texture = Texture.from(url, Object.assign({ resourceOptions }, options), !1), resource = texture.baseTexture.resource;
133 return texture.baseTexture.valid ? Promise.resolve(texture) : resource.load().then(() => Promise.resolve(texture));
134 }
135 /**
136 * Create a new Texture with a BufferResource from a typed array.
137 * @param buffer - The optional array to use. If no data is provided, a new Float32Array is created.
138 * @param width - Width of the resource
139 * @param height - Height of the resource
140 * @param options - See {@link PIXI.BaseTexture}'s constructor for options.
141 * Default properties are different from the constructor's defaults.
142 * @param {PIXI.FORMATS} [options.format] - The format is not given, the type is inferred from the
143 * type of the buffer: `RGBA` if Float32Array, Int8Array, Uint8Array, or Uint8ClampedArray,
144 * otherwise `RGBA_INTEGER`.
145 * @param {PIXI.TYPES} [options.type] - The type is not given, the type is inferred from the
146 * type of the buffer. Maps Float32Array to `FLOAT`, Int32Array to `INT`, Uint32Array to
147 * `UNSIGNED_INT`, Int16Array to `SHORT`, Uint16Array to `UNSIGNED_SHORT`, Int8Array to `BYTE`,
148 * Uint8Array/Uint8ClampedArray to `UNSIGNED_BYTE`.
149 * @param {PIXI.ALPHA_MODES} [options.alphaMode=PIXI.ALPHA_MODES.NPM]
150 * @param {PIXI.SCALE_MODES} [options.scaleMode=PIXI.SCALE_MODES.NEAREST]
151 * @returns - The resulting new BaseTexture
152 */
153 static fromBuffer(buffer, width, height, options) {
154 return new Texture(BaseTexture.BaseTexture.fromBuffer(buffer, width, height, options));
155 }
156 /**
157 * Create a texture from a source and add to the cache.
158 * @param {HTMLImageElement|HTMLVideoElement|ImageBitmap|PIXI.ICanvas|string} source - The input source.
159 * @param imageUrl - File name of texture, for cache and resolving resolution.
160 * @param name - Human readable name for the texture cache. If no name is
161 * specified, only `imageUrl` will be used as the cache ID.
162 * @param options
163 * @returns - Output texture
164 */
165 static fromLoader(source, imageUrl, name, options) {
166 const baseTexture = new BaseTexture.BaseTexture(source, Object.assign({
167 scaleMode: BaseTexture.BaseTexture.defaultOptions.scaleMode,
168 resolution: utils.getResolutionOfUrl(imageUrl)
169 }, options)), { resource } = baseTexture;
170 resource instanceof ImageResource.ImageResource && (resource.url = imageUrl);
171 const texture = new Texture(baseTexture);
172 return name || (name = imageUrl), BaseTexture.BaseTexture.addToCache(texture.baseTexture, name), Texture.addToCache(texture, name), name !== imageUrl && (BaseTexture.BaseTexture.addToCache(texture.baseTexture, imageUrl), Texture.addToCache(texture, imageUrl)), texture.baseTexture.valid ? Promise.resolve(texture) : new Promise((resolve) => {
173 texture.baseTexture.once("loaded", () => resolve(texture));
174 });
175 }
176 /**
177 * Adds a Texture to the global TextureCache. This cache is shared across the whole PIXI object.
178 * @param texture - The Texture to add to the cache.
179 * @param id - The id that the Texture will be stored against.
180 */
181 static addToCache(texture, id) {
182 id && (texture.textureCacheIds.includes(id) || texture.textureCacheIds.push(id), utils.TextureCache[id] && utils.TextureCache[id] !== texture && console.warn(`Texture added to the cache with an id [${id}] that already had an entry`), utils.TextureCache[id] = texture);
183 }
184 /**
185 * Remove a Texture from the global TextureCache.
186 * @param texture - id of a Texture to be removed, or a Texture instance itself
187 * @returns - The Texture that was removed
188 */
189 static removeFromCache(texture) {
190 if (typeof texture == "string") {
191 const textureFromCache = utils.TextureCache[texture];
192 if (textureFromCache) {
193 const index = textureFromCache.textureCacheIds.indexOf(texture);
194 return index > -1 && textureFromCache.textureCacheIds.splice(index, 1), delete utils.TextureCache[texture], textureFromCache;
195 }
196 } else if (texture?.textureCacheIds) {
197 for (let i = 0; i < texture.textureCacheIds.length; ++i)
198 utils.TextureCache[texture.textureCacheIds[i]] === texture && delete utils.TextureCache[texture.textureCacheIds[i]];
199 return texture.textureCacheIds.length = 0, texture;
200 }
201 return null;
202 }
203 /**
204 * Returns resolution of baseTexture
205 * @readonly
206 */
207 get resolution() {
208 return this.baseTexture.resolution;
209 }
210 /**
211 * The frame specifies the region of the base texture that this texture uses.
212 * Please call `updateUvs()` after you change coordinates of `frame` manually.
213 */
214 get frame() {
215 return this._frame;
216 }
217 set frame(frame) {
218 this._frame = frame, this.noFrame = !1;
219 const { x, y, width, height } = frame, xNotFit = x + width > this.baseTexture.width, yNotFit = y + height > this.baseTexture.height;
220 if (xNotFit || yNotFit) {
221 const relationship = xNotFit && yNotFit ? "and" : "or", errorX = `X: ${x} + ${width} = ${x + width} > ${this.baseTexture.width}`, errorY = `Y: ${y} + ${height} = ${y + height} > ${this.baseTexture.height}`;
222 throw new Error(`Texture Error: frame does not fit inside the base Texture dimensions: ${errorX} ${relationship} ${errorY}`);
223 }
224 this.valid = width && height && this.baseTexture.valid, !this.trim && !this.rotate && (this.orig = frame), this.valid && this.updateUvs();
225 }
226 /**
227 * Indicates whether the texture is rotated inside the atlas
228 * set to 2 to compensate for texture packer rotation
229 * set to 6 to compensate for spine packer rotation
230 * can be used to rotate or mirror sprites
231 * See {@link PIXI.groupD8} for explanation
232 */
233 get rotate() {
234 return this._rotate;
235 }
236 set rotate(rotate) {
237 this._rotate = rotate, this.valid && this.updateUvs();
238 }
239 /** The width of the Texture in pixels. */
240 get width() {
241 return this.orig.width;
242 }
243 /** The height of the Texture in pixels. */
244 get height() {
245 return this.orig.height;
246 }
247 /** Utility function for BaseTexture|Texture cast. */
248 castToBaseTexture() {
249 return this.baseTexture;
250 }
251 /** An empty texture, used often to not have to create multiple empty textures. Can not be destroyed. */
252 static get EMPTY() {
253 return Texture._EMPTY || (Texture._EMPTY = new Texture(new BaseTexture.BaseTexture()), removeAllHandlers(Texture._EMPTY), removeAllHandlers(Texture._EMPTY.baseTexture)), Texture._EMPTY;
254 }
255 /** A white texture of 16x16 size, used for graphics and other things Can not be destroyed. */
256 static get WHITE() {
257 if (!Texture._WHITE) {
258 const canvas = settings.settings.ADAPTER.createCanvas(16, 16), context = canvas.getContext("2d");
259 canvas.width = 16, canvas.height = 16, context.fillStyle = "white", context.fillRect(0, 0, 16, 16), Texture._WHITE = new Texture(BaseTexture.BaseTexture.from(canvas)), removeAllHandlers(Texture._WHITE), removeAllHandlers(Texture._WHITE.baseTexture);
260 }
261 return Texture._WHITE;
262 }
263}
264exports.Texture = Texture;
265//# sourceMappingURL=Texture.js.map