3dexperiments/src/engine/resource.js

98 lines
2.2 KiB
JavaScript

/* global XMLHttpRequest, Image */
const imgCache = {}
// Find the assets directory properly
function fixURI (path, a = '') {
const pn = window.location.pathname
if (path.indexOf('/assets') === -1) path = '/assets/' + a + path
if (pn === '/' || pn === '/index.html') return path
const assetsDir = pn + path
return assetsDir.replace(/\/\//g, '/')
}
function GET (url, istext) {
return new Promise((resolve, reject) => {
var xmlHttp = new XMLHttpRequest()
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState === 4 && xmlHttp.status === 200) {
resolve(xmlHttp.responseText)
} else if (xmlHttp.readyState === 4 && xmlHttp.status >= 400) {
const err = new Error(xmlHttp.status)
err.request = xmlHttp
reject(err)
}
}
xmlHttp.open('GET', fixURI(url), true)
istext && (xmlHttp.responseType = 'text')
xmlHttp.send(null)
})
}
function smartGET (data) {
if (typeof data === 'string') {
data = {
url: data,
type: 'text'
}
}
if (!data.type) data.type = 'text'
const istext = (data.type !== 'image' && data.type !== 'file')
const url = data.url
if (!url) throw new Error('URL is required!')
if (data.type === 'json') {
return new Promise((resolve, reject) => {
GET(url).then((dtext) => {
try {
const jsonp = JSON.parse(dtext)
return resolve(jsonp)
} catch (e) {
reject(e)
}
}, reject)
})
}
return GET(data.url, istext)
}
function loadImage (url) {
url = fixURI(url, 'textures/')
// Ensure we don't load a texture multiple times
if (imgCache[url]) return imgCache[url]
return new Promise((resolve, reject) => {
const img = new Image()
img.onload = function () {
imgCache[url] = img
resolve(img)
}
img.onerror = function (e) {
reject(e)
}
img.src = url
})
}
function imageToSampler (img) {
const canvas = document.createElement('canvas')
const ctx = canvas.getContext('2d')
canvas.width = img.width
canvas.height = img.height
ctx.drawImage(img, 0, 0, img.width, img.height)
return function (x, y) {
return ctx.getImageData(x, y, 1, 1).data
}
}
export default { GET: smartGET, imageToSampler, loadImage }