UNPKG

2.62 kBJavaScriptView Raw
1import { BaseTexture } from '../BaseTexture.mjs';
2import { autoDetectResource } from './autoDetectResource.mjs';
3import { Resource } from './Resource.mjs';
4
5class AbstractMultiResource extends Resource {
6 constructor(length, options) {
7 const { width, height } = options || {};
8 super(width, height);
9 this.items = [];
10 this.itemDirtyIds = [];
11 for (let i = 0; i < length; i++) {
12 const partTexture = new BaseTexture();
13 this.items.push(partTexture);
14 this.itemDirtyIds.push(-2);
15 }
16 this.length = length;
17 this._load = null;
18 this.baseTexture = null;
19 }
20 initFromArray(resources, options) {
21 for (let i = 0; i < this.length; i++) {
22 if (!resources[i]) {
23 continue;
24 }
25 if (resources[i].castToBaseTexture) {
26 this.addBaseTextureAt(resources[i].castToBaseTexture(), i);
27 } else if (resources[i] instanceof Resource) {
28 this.addResourceAt(resources[i], i);
29 } else {
30 this.addResourceAt(autoDetectResource(resources[i], options), i);
31 }
32 }
33 }
34 dispose() {
35 for (let i = 0, len = this.length; i < len; i++) {
36 this.items[i].destroy();
37 }
38 this.items = null;
39 this.itemDirtyIds = null;
40 this._load = null;
41 }
42 addResourceAt(resource, index) {
43 if (!this.items[index]) {
44 throw new Error(`Index ${index} is out of bounds`);
45 }
46 if (resource.valid && !this.valid) {
47 this.resize(resource.width, resource.height);
48 }
49 this.items[index].setResource(resource);
50 return this;
51 }
52 bind(baseTexture) {
53 if (this.baseTexture !== null) {
54 throw new Error("Only one base texture per TextureArray is allowed");
55 }
56 super.bind(baseTexture);
57 for (let i = 0; i < this.length; i++) {
58 this.items[i].parentTextureArray = baseTexture;
59 this.items[i].on("update", baseTexture.update, baseTexture);
60 }
61 }
62 unbind(baseTexture) {
63 super.unbind(baseTexture);
64 for (let i = 0; i < this.length; i++) {
65 this.items[i].parentTextureArray = null;
66 this.items[i].off("update", baseTexture.update, baseTexture);
67 }
68 }
69 load() {
70 if (this._load) {
71 return this._load;
72 }
73 const resources = this.items.map((item) => item.resource).filter((item) => item);
74 const promises = resources.map((item) => item.load());
75 this._load = Promise.all(promises).then(() => {
76 const { realWidth, realHeight } = this.items[0];
77 this.resize(realWidth, realHeight);
78 return Promise.resolve(this);
79 });
80 return this._load;
81 }
82}
83
84export { AbstractMultiResource };
85//# sourceMappingURL=AbstractMultiResource.mjs.map