Files
stemengine_old/muon-iframe/stemengine-bootstrap.js
2026-04-21 16:24:11 +09:00

97 lines
3.0 KiB
JavaScript

/* StemEngine runtime bootstrap injected into Muon build at image build-time. */
(function stemengineBootstrap() {
const REQUIRED_EXTENSIONS = ['OES_texture_float_linear', 'EXT_color_buffer_float']
function installContextCaptureHook() {
const originalGetContext = HTMLCanvasElement.prototype.getContext
if (typeof originalGetContext !== 'function') return
if (HTMLCanvasElement.prototype.__stemengineContextHookInstalled__) return
HTMLCanvasElement.prototype.getContext = function patchedGetContext(type, attrs) {
const ctx = originalGetContext.call(this, type, attrs)
if ((type === 'webgl2' || type === 'webgl') && ctx && this.isConnected) {
if (!window.__STEMENGINE_MUON_GL_CTX__) {
window.__STEMENGINE_MUON_GL_CTX__ = ctx
}
if (!window.__STEMENGINE_MUON_CANVAS__) {
window.__STEMENGINE_MUON_CANVAS__ = this
}
}
return ctx
}
Object.defineProperty(HTMLCanvasElement.prototype, '__stemengineContextHookInstalled__', {
value: true,
configurable: true,
writable: false,
enumerable: false,
})
}
function checkBaseline() {
const canvas = document.createElement('canvas')
const gl = canvas.getContext('webgl2') || canvas.getContext('webgl')
if (!gl) {
console.warn('[StemEngine][Muon] WebGL unavailable; fallback mode should be used.')
return {
ok: false,
missing: ['webgl'],
}
}
const missing = REQUIRED_EXTENSIONS.filter((name) => !gl.getExtension(name))
if (missing.length > 0) {
console.warn('[StemEngine][Muon] Missing required WebGL extensions:', missing.join(', '))
return { ok: false, missing }
}
return { ok: true, missing: [] }
}
function installContextLifecycleHooks() {
let retries = 0
const maxRetries = 120
const attach = () => {
const canvas = document.querySelector('canvas.webgl') || document.querySelector('canvas')
if (!canvas) {
retries += 1
if (retries <= maxRetries) requestAnimationFrame(attach)
return
}
canvas.addEventListener('webglcontextlost', (event) => {
event.preventDefault()
console.warn('[StemEngine][Muon] webglcontextlost')
window.__STEMENGINE_MUON_CONTEXT_LOST__ = true
})
canvas.addEventListener('webglcontextrestored', () => {
console.info('[StemEngine][Muon] webglcontextrestored')
window.__STEMENGINE_MUON_CONTEXT_LOST__ = false
})
}
attach()
}
if (typeof window.__STEMENGINE_MUON_STOP_FN__ !== 'function') {
window.__STEMENGINE_MUON_STOP_FN__ = function stemengineNoopStop() {}
}
if (typeof window.__STEMENGINE_MUON_RESUME_FN__ !== 'function') {
window.__STEMENGINE_MUON_RESUME_FN__ = function stemengineNoopResume() {}
}
installContextCaptureHook()
const baseline = checkBaseline()
window.__STEMENGINE_MUON_WEBGL_BASELINE__ = baseline
if (!baseline.ok) {
document.documentElement.classList.add('stemengine-muon-degraded')
}
installContextLifecycleHooks()
})()