mirror of https://github.com/mode777/rayjs.git
47 lines
1.3 KiB
TypeScript
47 lines
1.3 KiB
TypeScript
|
type ResourceType = 'texture' | 'image' | 'shader' | 'font'
|
||
|
|
||
|
const resourceList = new Map<string, Resource>()
|
||
|
|
||
|
interface Resource {
|
||
|
refcount: number,
|
||
|
id: string,
|
||
|
resource: any
|
||
|
unload: (t: any) => void
|
||
|
}
|
||
|
|
||
|
function loadResourceFunc<T>(loader: (filename: string) => T, unloader: (resource: T) => void){
|
||
|
return (filename: string) => {
|
||
|
if(resourceList.has(filename)){
|
||
|
const res = resourceList.get(filename)
|
||
|
res!.refcount++
|
||
|
return <T>res?.resource
|
||
|
} else {
|
||
|
traceLog(LOG_INFO, "here")
|
||
|
const resource = loader(filename)
|
||
|
traceLog(LOG_INFO, <string>resource)
|
||
|
resourceList.set(filename, {
|
||
|
refcount: 1,
|
||
|
id: filename,
|
||
|
resource: resource,
|
||
|
unload: unloader
|
||
|
})
|
||
|
return resource
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
export const resourceUnload = (id: string) => {
|
||
|
const res = resourceList.get(id)
|
||
|
if(res){
|
||
|
res.refcount--
|
||
|
if(res.refcount === 0){
|
||
|
res.unload(res.resource)
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
export const resourceUnloadAll = () => {
|
||
|
for (const res of resourceList.entries()) {
|
||
|
res[1].unload(res[1].resource)
|
||
|
}
|
||
|
}
|
||
|
export const textureLoad = loadResourceFunc<Texture>(loadTexture,unloadTexture)
|
||
|
export const fontLoad = loadResourceFunc<Font>(loadFont,unloadFont)
|