| 52 | } |
| 53 | |
| 54 | export class DefaultImageProvider implements ImageProvider { |
| 55 | readonly nullTexture: Texture = createTexture('__NULL_TEXTURE', NULL_IMAGE_URI); |
| 56 | readonly loadingTexture: Texture = createTexture('__LOADING_TEXTURE', LOADING_IMAGE_URI); |
| 57 | |
| 58 | private _cache = new Map<Uint8Array<ArrayBuffer>, Texture | CompressedTexture>(); |
| 59 | private _ktx2Loader: KTX2Loader | null = null; |
| 60 | |
| 61 | async initTexture(textureDef: TextureDef): Promise<void> { |
| 62 | await this.getTexture(textureDef); |
| 63 | } |
| 64 | |
| 65 | async getTexture(textureDef: TextureDef): Promise<Texture | CompressedTexture> { |
| 66 | const image = textureDef.getImage()!; |
| 67 | const mimeType = textureDef.getMimeType(); |
| 68 | |
| 69 | let texture = this._cache.get(image); |
| 70 | |
| 71 | if (texture) return texture; |
| 72 | |
| 73 | texture = mimeType === 'image/ktx2' ? await this._loadKTX2Image(image) : await this._loadImage(image, mimeType); |
| 74 | |
| 75 | this._cache.set(image, texture); |
| 76 | return texture; |
| 77 | } |
| 78 | |
| 79 | setKTX2Loader(loader: KTX2Loader): this { |
| 80 | this._ktx2Loader = loader; |
| 81 | return this; |
| 82 | } |
| 83 | |
| 84 | clear(): void { |
| 85 | for (const [_, texture] of this._cache) { |
| 86 | texture.dispose(); |
| 87 | } |
| 88 | this._cache.clear(); |
| 89 | } |
| 90 | |
| 91 | dispose(): void { |
| 92 | this.clear(); |
| 93 | if (this._ktx2Loader) this._ktx2Loader.dispose(); |
| 94 | } |
| 95 | |
| 96 | /** Load PNG, JPEG, or other browser-supported image format. */ |
| 97 | private async _loadImage(image: Uint8Array<ArrayBuffer>, mimeType: string): Promise<Texture> { |
| 98 | return new Promise((resolve, reject) => { |
| 99 | const blob = new Blob([image], { type: mimeType }); |
| 100 | const imageURL = URL.createObjectURL(blob); |
| 101 | const imageEl = document.createElement('img'); |
| 102 | |
| 103 | const texture = new Texture(imageEl); |
| 104 | texture.flipY = false; |
| 105 | |
| 106 | imageEl.src = imageURL; |
| 107 | imageEl.onload = () => { |
| 108 | URL.revokeObjectURL(imageURL); |
| 109 | resolve(texture); |
| 110 | }; |
| 111 | imageEl.onerror = reject; |
nothing calls this directly
no test coverage detected