UNPKG

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