95 lines
2.4 KiB
TypeScript
Raw Normal View History

2024-03-01 22:04:57 -07:00
import { type SpriteSpec, SPRITE_SPECS } from ".";
import { SOUND_SPECS, SoundSpec } from "./sounds";
2024-03-01 18:56:58 -07:00
2024-03-10 00:52:37 -07:00
let BASE_URL = import.meta.env.BASE_URL || document.location;
BASE_URL = BASE_URL.endsWith("/") ? BASE_URL.slice(0, -1) : BASE_URL;
2024-03-09 21:51:22 -07:00
export const FONT = new FontFace(
"scientifica",
2024-03-10 00:52:37 -07:00
`url(${BASE_URL}/fonts/scientifica.ttf)`
2024-03-09 21:51:22 -07:00
);
2024-03-02 04:02:20 -07:00
FONT.load().then((font) => {
document.fonts.add(font);
});
2024-03-01 18:56:58 -07:00
export const IMAGES = new Map<string, HTMLImageElement>();
export const SOUNDS = new Map<string, HTMLAudioElement>();
2024-03-01 18:56:58 -07:00
export const loadSpritesIntoImageElements = (
2024-03-09 21:51:22 -07:00
spriteSpecs: Partial<SpriteSpec>[]
2024-03-01 18:56:58 -07:00
): Promise<void>[] => {
const spritePromises: Promise<void>[] = [];
for (const spriteSpec of spriteSpecs) {
if (spriteSpec.sheet) {
const img = new Image();
2024-03-09 21:51:22 -07:00
img.src = BASE_URL + spriteSpec.sheet;
2024-03-01 18:56:58 -07:00
IMAGES.set(spriteSpec.sheet, img);
spritePromises.push(
new Promise((resolve) => {
img.onload = () => resolve();
2024-03-09 21:51:22 -07:00
})
2024-03-01 18:56:58 -07:00
);
}
if (spriteSpec.states) {
spritePromises.push(
2024-03-09 21:51:22 -07:00
...loadSpritesIntoImageElements(Array.from(spriteSpec.states.values()))
2024-03-01 18:56:58 -07:00
);
}
}
return spritePromises;
};
export const loadSoundsIntoAudioElements = (
2024-03-09 21:51:22 -07:00
soundSpecs: SoundSpec[]
): Promise<void>[] => {
const soundPromises: Promise<void>[] = [];
for (const soundSpec of soundSpecs) {
if (soundSpec.url) {
2024-03-09 21:51:22 -07:00
const promise = fetch(BASE_URL + soundSpec.url)
.then((response) => response.blob())
.then((blob) => {
const audio = new Audio();
audio.src = URL.createObjectURL(blob);
audio.volume = soundSpec.volume ?? 1;
SOUNDS.set(soundSpec.name, audio);
return new Promise<void>((resolve, rej) => {
audio.oncanplaythrough = () => {
resolve();
};
audio.onerror = (e) => {
console.error(soundSpec);
rej(e);
};
});
});
soundPromises.push(promise);
}
if (soundSpec.states) {
soundPromises.push(
2024-03-09 21:51:22 -07:00
...loadSoundsIntoAudioElements(Array.from(soundSpec.states.values()))
);
}
}
return soundPromises;
};
2024-03-01 18:56:58 -07:00
export const loadAssets = () =>
Promise.all([
...loadSpritesIntoImageElements(
Array.from(SPRITE_SPECS.keys()).map(
2024-03-09 21:51:22 -07:00
(key) => SPRITE_SPECS.get(key) as SpriteSpec
)
2024-03-01 18:56:58 -07:00
),
2024-03-02 04:02:20 -07:00
FONT.load(),
...loadSoundsIntoAudioElements(Array.from(SOUND_SPECS.values())),
2024-03-01 18:56:58 -07:00
]);