three-game-engine
Version:
Simple light-weight game engine using three.js, three-mesh-ui and rapier
77 lines (76 loc) • 2.83 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
const GLTFAsset_1 = require("./GLTFAsset");
const TextureAsset_1 = require("./TextureAsset");
const SoundAsset_1 = require("./SoundAsset");
const JSONAsset_1 = require("./JSONAsset");
class AssetStore {
constructor(baseURLorDirHandle) {
if (typeof baseURLorDirHandle === 'string') {
this.baseURL = baseURLorDirHandle;
if (this.baseURL.endsWith('/')) {
this.baseURL = this.baseURL.slice(0, this.baseURL.length - 1);
}
this.dirHandle = null;
}
else {
this.baseURL = null;
this.dirHandle = baseURLorDirHandle;
}
this.loadedAssets = {}; // key/value pairs (url is key, asset is value) all files currently loaded
}
static _getAssetSubclass(path) {
const assetTypes = [
{ subclass: GLTFAsset_1.default, fileExtensions: ['.gltf', '.glb'] },
{ subclass: TextureAsset_1.default, fileExtensions: ['.png', '.jpg', '.bmp'] },
{ subclass: SoundAsset_1.default, fileExtensions: ['.wav', '.mp3', 'ogg'] },
{ subclass: JSONAsset_1.default, fileExtensions: ['.json'] }
];
if (path.includes('cube_textures')) {
return;
}
else {
const assetType = assetTypes.find(type => type.fileExtensions.some(ext => path.endsWith(ext)));
if (assetType) {
return assetType.subclass;
}
else {
throw new Error(`Unable to identify which Asset Subclass to use for this asset: ${path}`);
}
}
}
/**
* Fetches the specified asset (if not already fetched)
**/
async load(path) {
if (!this.loadedAssets[path]) {
const AssetSubclass = AssetStore._getAssetSubclass(path);
const asset = new AssetSubclass(this.baseURL || this.dirHandle, path);
await asset.load();
this.loadedAssets[path] = asset;
console.log(`AssetStore: successfully loaded asset: ${path}`);
}
return this.loadedAssets[path];
}
get(path) {
return this.loadedAssets[path];
}
unload(path) {
const asset = this.loadedAssets[path];
if (asset) {
asset.unload();
this.loadedAssets[path] = null;
console.log(`Assets: unloaded ${path}`);
}
else {
console.log(`Assets: unloading ${path} - skipped, not currently loaded`);
}
}
unloadAll() {
console.log(`AssetStore: unloading all assets, clearing this store.`);
Object.keys(this.loadedAssets).forEach(assetPath => {
this.unload(assetPath);
});
}
}
exports.default = AssetStore;
;