Skip to content
This repository has been archived by the owner on Nov 12, 2024. It is now read-only.

Commit

Permalink
fix loadRoot not working sometimes
Browse files Browse the repository at this point in the history
  • Loading branch information
slmjkdbtl committed Nov 7, 2023
1 parent 42f1060 commit 4eaf565
Show file tree
Hide file tree
Showing 6 changed files with 126 additions and 86 deletions.
10 changes: 7 additions & 3 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
### v3000.1.15
- fixed `loadRoot()` not working sometimes
- fixed audio being resumed when the tab is switched on but `debug.paused` is true

### v3000.1.12
- fix `color()` and `rgb()` not working
- fixed `color()` and `rgb()` not working

### v3000.1.11
- added option `kaboom({ focus: false })` to disable focus on start
Expand All @@ -8,11 +12,11 @@
- added `Color#toHSL()`

### v3000.1.10
- fix test code accidentally getting shipped (where a screenshot will be downloaded every time you press space)
- fixed test code accidentally getting shipped (where a screenshot will be downloaded every time you press space)

### v3000.1.9
- added `fill` option to `rect()`, `circle()` and `sprite()`
- fix view getting cut off in letterbox mode
- fixed view getting cut off in letterbox mode

### v3000.1.8
- fixed `scale` option acting weird when width and height are defined (by @hirnsalat)
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "kaboom",
"description": "kaboom.js is a JavaScript library that helps you make games fast and fun!",
"version": "3000.1.13",
"version": "3000.1.15",
"license": "MIT",
"homepage": "https://kaboomjs.com/",
"repository": "github:replit/kaboom",
Expand Down
79 changes: 25 additions & 54 deletions src/assets.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import {
Event,
isDataURL,
} from "./utils"

export class Asset<D> {
Expand Down Expand Up @@ -100,61 +99,33 @@ export class AssetBucket<D> {
}
}

export default () => {

const state = {
urlPrefix: "",
loaded: false,
}

function setURLPrefix(prefix: string) {
state.urlPrefix = prefix
}

function getURLPrefix() {
return state.urlPrefix
}

function fetchURL(path: string) {
const url = state.urlPrefix + path
return fetch(url)
.then((res) => {
if (!res.ok) throw new Error(`Failed to fetch "${url}"`)
return res
})
}

function fetchJSON(path: string) {
return fetchURL(path).then((res) => res.json())
}

function fetchText(path: string) {
return fetchURL(path).then((res) => res.text())
}
export function fetchURL(url: string) {
return fetch(url)
.then((res) => {
if (!res.ok) throw new Error(`Failed to fetch "${url}"`)
return res
})
}

function fetchArrayBuffer(path: string) {
return fetchURL(path).then((res) => res.arrayBuffer())
}
export function fetchJSON(path: string) {
return fetchURL(path).then((res) => res.json())
}

// wrapper around image loader to get a Promise
function loadImg(src: string): Promise<HTMLImageElement> {
const img = new Image()
img.crossOrigin = "anonymous"
img.src = isDataURL(src) ? src : state.urlPrefix + src
return new Promise<HTMLImageElement>((resolve, reject) => {
img.onload = () => resolve(img)
img.onerror = () => reject(new Error(`Failed to load image from "${src}"`))
})
}
export function fetchText(path: string) {
return fetchURL(path).then((res) => res.text())
}

return {
setURLPrefix,
getURLPrefix,
loadImg,
fetchURL,
fetchJSON,
fetchText,
fetchArrayBuffer,
}
export function fetchArrayBuffer(path: string) {
return fetchURL(path).then((res) => res.arrayBuffer())
}

// wrapper around image loader to get a Promise
export function loadImg(src: string): Promise<HTMLImageElement> {
const img = new Image()
img.crossOrigin = "anonymous"
img.src = src
return new Promise<HTMLImageElement>((resolve, reject) => {
img.onload = () => resolve(img)
img.onerror = () => reject(new Error(`Failed to load image from "${src}"`))
})
}
76 changes: 52 additions & 24 deletions src/kaboom.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const VERSION = "3000.1.13"
const VERSION = "3000.1.15"

import initApp from "./app"
import initGfx, {
Expand All @@ -8,9 +8,13 @@ import initGfx, {
BatchRenderer,
} from "./gfx"

import initAssets, {
import {
Asset,
AssetBucket,
fetchArrayBuffer,
fetchJSON,
fetchText,
loadImg,
} from "./assets"

import {
Expand Down Expand Up @@ -63,7 +67,7 @@ import {
downloadBlob,
uid,
isDataURL,
getExt,
getFileName,
overload2,
dataURLToArrayBuffer,
EventController,
Expand Down Expand Up @@ -96,6 +100,7 @@ import type {
Vertex,
BitmapFontData,
ShaderData,
AsepriteData,
LoadSpriteSrc,
LoadSpriteOpt,
SpriteAtlasData,
Expand Down Expand Up @@ -431,8 +436,6 @@ export default (gopt: KaboomOpt = {}): KaboomCtx => {
texFilter: gopt.texFilter,
})

const ass = initAssets()

const gfx = (() => {

const defShader = makeShader(DEF_VERT, DEF_FRAG)
Expand All @@ -452,13 +455,13 @@ export default (gopt: KaboomOpt = {}): KaboomCtx => {
let bgAlpha = 1

if (gopt.background) {
bgColor = Color.fromArray(gopt.background)
bgAlpha = gopt.background[3] ?? 1
bgColor = rgb(gopt.background)
bgAlpha = Array.isArray(gopt.background) ? gopt.background[3] : 1
gl.clearColor(
bgColor.r / 255,
bgColor.g / 255,
bgColor.b / 255,
bgAlpha,
bgAlpha ?? 1,
)
}

Expand Down Expand Up @@ -567,7 +570,7 @@ export default (gopt: KaboomOpt = {}): KaboomCtx => {
}

static fromURL(url: string, opt: LoadSpriteOpt = {}): Promise<SpriteData> {
return ass.loadImg(url).then((img) => SpriteData.fromImage(img, opt))
return loadImg(url).then((img) => SpriteData.fromImage(img, opt))
}

}
Expand All @@ -590,7 +593,7 @@ export default (gopt: KaboomOpt = {}): KaboomCtx => {
if (isDataURL(url)) {
return SoundData.fromArrayBuffer(dataURLToArrayBuffer(url))
} else {
return ass.fetchArrayBuffer(url).then((buf) => SoundData.fromArrayBuffer(buf))
return fetchArrayBuffer(url).then((buf) => SoundData.fromArrayBuffer(buf))
}
}

Expand Down Expand Up @@ -624,6 +627,7 @@ export default (gopt: KaboomOpt = {}): KaboomCtx => {
})()

const assets = {
urlPrefix: "",
// asset holders
sprites: new AssetBucket<SpriteData>(),
fonts: new AssetBucket<FontData>(),
Expand All @@ -636,6 +640,11 @@ export default (gopt: KaboomOpt = {}): KaboomCtx => {
loaded: false,
}

function fixURL<D>(url: D): D {
if (typeof url !== "string" || isDataURL(url)) return url
return assets.urlPrefix + url as D
}

const game = {

// general events
Expand Down Expand Up @@ -717,22 +726,27 @@ export default (gopt: KaboomOpt = {}): KaboomCtx => {
// global load path prefix
function loadRoot(path?: string): string {
if (path !== undefined) {
ass.setURLPrefix(path)
assets.urlPrefix = path
}
return ass.getURLPrefix()
return assets.urlPrefix
}

function loadJSON(name, url) {
return assets.custom.add(name, ass.fetchJSON(url))
return assets.custom.add(name, fetchJSON(url))
}

class FontData {
fontface: FontFace
filter: TexFilter = DEF_FONT_FILTER
outline: Outline | null = null
size: number = DEF_TEXT_CACHE_SIZE
constructor(face: FontFace, opt: LoadFontOpt = {}) {
this.fontface = face
this.filter = opt.filter ?? DEF_FONT_FILTER
this.size = opt.size ?? DEF_TEXT_CACHE_SIZE
if (this.size > MAX_TEXT_CACHE_SIZE) {
throw new Error(`Max font size: ${MAX_TEXT_CACHE_SIZE}`)
}
if (opt.outline) {
this.outline = {
width: 1,
Expand Down Expand Up @@ -770,7 +784,7 @@ export default (gopt: KaboomOpt = {}): KaboomCtx => {
gh: number,
opt: LoadBitmapFontOpt = {},
): Asset<BitmapFontData> {
return assets.bitmapFonts.add(name, ass.loadImg(src)
return assets.bitmapFonts.add(name, loadImg(src)
.then((img) => {
return makeFont(
Texture.fromImage(ggl, img, opt),
Expand Down Expand Up @@ -805,9 +819,10 @@ export default (gopt: KaboomOpt = {}): KaboomCtx => {
src: LoadSpriteSrc,
data: SpriteAtlasData | string,
): Asset<Record<string, SpriteData>> {
src = fixURL(src)
if (typeof data === "string") {
return load(new Promise((res, rej) => {
ass.fetchJSON(data).then((json) => {
fetchJSON(data).then((json) => {
loadSpriteAtlas(src, json).then(res).catch(rej)
})
}))
Expand Down Expand Up @@ -875,12 +890,13 @@ export default (gopt: KaboomOpt = {}): KaboomCtx => {
anims: {},
},
): Asset<SpriteData> {
src = fixURL(src)
if (Array.isArray(src)) {
if (src.some((s) => typeof s === "string")) {
return assets.sprites.add(
name,
Promise.all(src.map((s) => {
return typeof s === "string" ? ass.loadImg(s) : Promise.resolve(s)
return typeof s === "string" ? loadImg(s) : Promise.resolve(s)
})).then((images) => createSpriteSheet(images, opt)),
)
} else {
Expand All @@ -897,11 +913,13 @@ export default (gopt: KaboomOpt = {}): KaboomCtx => {

function loadPedit(name: string | null, src: string | PeditFile): Asset<SpriteData> {

src = fixURL(src)

// eslint-disable-next-line
return assets.sprites.add(name, new Promise(async (resolve) => {

const data = typeof src === "string" ? await ass.fetchJSON(src) : src
const images = await Promise.all(data.frames.map(ass.loadImg))
const data = typeof src === "string" ? await fetchJSON(src) : src
const images = await Promise.all(data.frames.map(loadImg))
const canvas = document.createElement("canvas")
canvas.width = data.width
canvas.height = data.height * data.frames.length
Expand All @@ -926,15 +944,21 @@ export default (gopt: KaboomOpt = {}): KaboomCtx => {
function loadAseprite(
name: string | null,
imgSrc: LoadSpriteSrc,
jsonSrc: string,
jsonSrc: string | AsepriteData,
): Asset<SpriteData> {

imgSrc = fixURL(imgSrc)
jsonSrc = fixURL(jsonSrc)

if (typeof imgSrc === "string" && !jsonSrc) {
jsonSrc = imgSrc.replace(new RegExp(`${getExt(imgSrc)}$`), "json")
jsonSrc = getFileName(imgSrc) + ".json"
}

const resolveJSON = typeof jsonSrc === "string"
? ass.fetchJSON(jsonSrc)
? fetchJSON(jsonSrc)
: Promise.resolve(jsonSrc)
return assets.sprites.add(name, resolveJSON.then((data) => {

return assets.sprites.add(name, resolveJSON.then((data: AsepriteData) => {
const size = data.meta.size
const frames = data.frames.map((f: any) => {
return new Quad(
Expand Down Expand Up @@ -963,6 +987,7 @@ export default (gopt: KaboomOpt = {}): KaboomCtx => {
anims: anims,
})
}))

}

function loadShader(
Expand All @@ -978,9 +1003,11 @@ export default (gopt: KaboomOpt = {}): KaboomCtx => {
vert?: string,
frag?: string,
): Asset<ShaderData> {
vert = fixURL(vert)
frag = fixURL(frag)
const resolveUrl = (url?: string) =>
url
? ass.fetchText(url)
? fetchText(url)
: Promise.resolve(null)
const load = Promise.all([resolveUrl(vert), resolveUrl(frag)])
.then(([vcode, fcode]: [string | null, string | null]) => {
Expand All @@ -995,6 +1022,7 @@ export default (gopt: KaboomOpt = {}): KaboomCtx => {
name: string | null,
src: string | ArrayBuffer,
): Asset<SoundData> {
src = fixURL(src)
return assets.sounds.add(
name,
typeof src === "string"
Expand Down Expand Up @@ -6183,7 +6211,7 @@ export default (gopt: KaboomOpt = {}): KaboomCtx => {
})

app.onShow(() => {
if (!gopt.backgroundAudio) {
if (!gopt.backgroundAudio && !debug.paused) {
audio.ctx.resume()
}
})
Expand Down
Loading

0 comments on commit 4eaf565

Please sign in to comment.