Files
pihkaal-me/app/composables/useAssets.ts.in

67 lines
1.3 KiB
TypeScript

import * as THREE from "three";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
const imageCache = new Map<string, HTMLImageElement>();
const modelCache = new Map<string, THREE.Group>();
const loaded = ref(0);
const total = ref({{TOTAL}});
const isReady = computed(() => loaded.value === total.value);
const createImage = (path: string) => {
if (imageCache.has(path)) {
return imageCache.get(path)!;
}
const img = document.createElement('img');
img.src = path;
imageCache.set(path, img);
if (img.complete) {
loaded.value += 1;
} else {
img.onload = () => { loaded.value += 1 };
}
return img;
};
const createModel = (path: string) => {
const cached = modelCache.get(path);
if (cached) {
return cached;
}
const model = new THREE.Group();
modelCache.set(path, model);
new GLTFLoader().load(
path,
(gltf) => {
for (const child of [...gltf.scene.children]) {
model.add(child);
}
loaded.value += 1;
},
undefined,
(error) => {
console.error(`Error loading model ${path}:`, error);
loaded.value += 1;
}
);
return model;
};
const assets = {{ASSETS}};
export const useAssets = () => {
return {
assets,
loaded,
total,
isReady,
};
};