class Scene { static idCount = 0; id = null; activeObjects = []; position = null; size = null; real_position = null; px = 0; py = 0; real_size = null; cameraPosition = null; parentScene = null; renderBackground = true; quadTree = null; pendingRemoval = []; _sortedActiveObjects = null; _sortDirty = true; /** Objects whose `layer` changed since the last draw-order rebuild. */ _layerChanged = []; /** * If more than this many objects change layer between draws, fall back to a * full in-place sort (cheaper than many splice reinserts on large lists). */ _layerChangeFullSortThreshold = 64; /** Reused per-draw-layer object lists (cleared + refilled each draw). */ _byLayer = null; _byLayerNames = null; g_primary = false; static DisplayModes = { absolute: 0, relativeToParent: 1 }; displayMode = Scene.DisplayModes.absolute; cv_canvas = null; glContext = null; destroyed = false; // Legacy: posts applied to the "default" layer when that layer has none of its own. postShaders = []; postTime = 0; // Ordered list of RenderLayer. Index 0 is drawn first (back). renderLayers = null; game = null; get primary () { return this.g_primary; } constructor (x, y, width, height, displayMode = 0) { Scene.idCount++; this.id = 'canvas_' + Scene.idCount; this.position = new vector(x, y); this.size = new vector(width, height); this.real_position = new vector(x, y); this.real_size = new vector(width, height); this.cameraPosition = new vector(0, 0); this.displayMode = displayMode; const body = document.body; body.insertAdjacentHTML('beforeend', ''); this.cv_canvas = document.getElementById(this.id); this.glContext = new GLContext(this.cv_canvas); this.postShaders = []; this.postTime = 0; this.renderLayers = [new RenderLayer(RenderLayer.DEFAULT_NAME)]; this.g_fixSize(); this.quadTree = new QuadTree(this.real_size.x, this.real_size.y); } /** * Replace the layer stack. Order in the array is draw order (first = back). * Each entry: RenderLayer, or { name, postShaders?, composite? }. */ setLayers (layerConfigs) { if (!layerConfigs || !layerConfigs.length) { this.renderLayers = [new RenderLayer(RenderLayer.DEFAULT_NAME)]; return this.renderLayers; } const layers = []; for (let i = 0; i < layerConfigs.length; i++) { const cfg = layerConfigs[i]; if (!cfg) { continue; } if (cfg instanceof RenderLayer) { layers.push(cfg); } else { layers.push(new RenderLayer(cfg.name, cfg)); } } if (!layers.length) { layers.push(new RenderLayer(RenderLayer.DEFAULT_NAME)); } this.renderLayers = layers; return this.renderLayers; } getLayer (name) { const layers = this.renderLayers || []; for (let i = 0; i < layers.length; i++) { if (layers[i].name === name) { return layers[i]; } } return null; } setPrimary () { this.game.setPrimaryScene(this); } onLoad () { } loadChildScene (scene) { scene.parentScene = this; this.game.loadScene(scene); } destroy () { if (this.destroyed) { return; } for (var i = 0; i < this.activeObjects.length; i++) { this.activeObjects[i].destroy(); } this.destroyed = true; if (this.game) { this.game.removeScene(this); } this.removeCanvas(); if (this.primary) { if (this.parentScene && !this.parentScene.destroyed) { this.parentScene.setPrimary(); } else if (this.game) { let promoted = null; for (let i = 0; i < this.game.activeScenes.length; i++) { const candidate = this.game.activeScenes[i]; if (candidate !== this && !candidate.destroyed) { promoted = candidate; break; } } if (promoted) { this.game.setPrimaryScene(promoted); } else { this.g_primary = false; } } else { this.g_primary = false; } } } removeCanvas () { var elem = this.cv_canvas || document.getElementById(this.id); if (elem && elem.parentNode) { elem.parentNode.removeChild(elem); } this.cv_canvas = null; this.glContext = null; } backgroundColor = { r: 255, g: 255, b: 255 }; get canvas () { return this.cv_canvas; } get context () { return this.glContext ? this.glContext.gl : null; } addObject (obj) { if (this.destroyed) { return; } this.activeObjects.push(obj); obj.scene = this; obj.initQuadtree(this.quadTree); obj.checkQuadtree(); if (this._sortedActiveObjects && !this._sortDirty && !this._layerChanged.length) { this.#insertSortedByLayer(this._sortedActiveObjects, obj); } else { this._sortDirty = true; } obj.addedToScene && obj.addedToScene(); return obj; } removeObject (obj) { if (this.activeObjects.indexOf(obj) >= 0) { if (!this.pendingRemoval.contains(obj)) { this.pendingRemoval.push(obj); } this._sortDirty = true; } if (this.quadTree === obj.quadTree) { this.quadTree.remove(obj); } } /** * Called when an object's draw-priority `layer` changes. * Batches small moves for splice-reinsert; floods into a full sort when many change. */ objectLayerChanged (obj) { if (!obj || this._sortDirty) { this._sortDirty = true; return; } this._layerChanged.push(obj); if (this._layerChanged.length > this._layerChangeFullSortThreshold) { this._sortDirty = true; this._layerChanged.length = 0; } } /** Force a full draw-order rebuild on the next draw (e.g. bulk external edits). */ markSortDirty () { this._sortDirty = true; this._layerChanged.length = 0; } /** First index with layer strictly greater than `layer` (insert after equal layers). */ #upperBoundByLayer (sorted, layer) { let lo = 0; let hi = sorted.length; while (lo < hi) { const mid = (lo + hi) >> 1; if (sorted[mid].layer <= layer) { lo = mid + 1; } else { hi = mid; } } return lo; } #insertSortedByLayer (sorted, obj) { // New objects and layer moves land after existing equal layers so a // recently updated sprite draws on top of older ties (stable-with-recency). const at = this.#upperBoundByLayer(sorted, obj.layer); sorted.splice(at, 0, obj); } #reinsertSortedByLayer (sorted, obj) { const from = sorted.indexOf(obj); if (from >= 0) { sorted.splice(from, 1); } this.#insertSortedByLayer(sorted, obj); } /** * Ensure `_sortedActiveObjects` matches `activeObjects` ordered by `layer`. * Avoids allocating a fresh array every frame (no `slice().sort()`). */ #ensureDrawOrder () { const active = this.activeObjects; if (this._sortDirty || !this._sortedActiveObjects) { let sorted = this._sortedActiveObjects; if (!sorted) { sorted = new Array(active.length); this._sortedActiveObjects = sorted; } else if (sorted.length !== active.length) { sorted.length = active.length; } for (let i = 0; i < active.length; i++) { sorted[i] = active[i]; } sorted.sort((a, b) => a.layer - b.layer); this._sortDirty = false; this._layerChanged.length = 0; return; } if (!this._layerChanged.length) { return; } const changed = this._layerChanged; const sorted = this._sortedActiveObjects; for (let i = 0; i < changed.length; i++) { this.#reinsertSortedByLayer(sorted, changed[i]); } changed.length = 0; } update (deltaTime) { if (this.destroyed) { return; } this.postTime += deltaTime; for (let i = 0; i < this.activeObjects.length; i++) { this.activeObjects[i].update(deltaTime); } if (this.pendingRemoval.length) { for (let i = 0; i < this.pendingRemoval.length; i++) { const obj = this.pendingRemoval[i]; const index = this.activeObjects.indexOf(obj); if (index >= 0 && obj.destroyed) { this.activeObjects.removeAt(index); } } this.pendingRemoval.length = 0; this._sortDirty = true; this._layerChanged.length = 0; } this.quadTree.update(deltaTime); } g_fixSize () { if (this.displayMode == Scene.DisplayModes.relativeToParent) { if (this.parentScene) { this.real_position.x = this.parentScene.real_position.x + (this.position.x * this.parentScene.real_size.x); this.real_position.y = this.parentScene.real_position.y + (this.position.y * this.parentScene.real_size.y); this.real_size.x = this.parentScene.real_size.x * this.size.x; this.real_size.y = this.parentScene.real_size.y * this.size.y; } else { this.real_position.x = window.innerWidth * this.position.x; this.real_position.y = window.innerHeight * this.position.y; this.real_size.x = window.innerWidth * this.size.x; this.real_size.y = window.innerHeight * this.size.y; } } else if (this.displayMode == Scene.DisplayModes.absolute) { this.real_position.x = this.position.x; this.real_position.y = this.position.y; this.real_size.x = this.size.x; this.real_size.y = this.size.y; } const canvasW = Math.max(1, Math.round(this.real_size.x)); const canvasH = Math.max(1, Math.round(this.real_size.y)); let resized = false; if (this.canvas.width != canvasW) { this.canvas.width = canvasW; resized = true; } if (this.canvas.height != canvasH) { this.canvas.height = canvasH; resized = true; } // Changing canvas dimensions resets WebGL — rebuild helper/buffers/programs. if (resized || !this.glContext) { this.glContext = new GLContext(this.cv_canvas); } else { this.glContext.setSize(this.canvas.width, this.canvas.height); } if (this.px != this.real_position.x) { this.px = this.real_position.x; this.canvas.style.left = this.real_position.x + "px"; } if (this.py != this.real_position.y) { this.py = this.real_position.y; this.canvas.style.top = this.real_position.y + "px"; } } normalizePostShaderList (list) { if (!list || !list.length) { return []; } const passes = []; for (let i = 0; i < list.length; i++) { const entry = list[i]; if (!entry) { continue; } if (entry instanceof Shader || (entry.vertSource && entry.fragSource && entry.getProgramInfo)) { passes.push({ shader: entry, uniforms: null }); } else if (entry.shader) { const pass = { shader: entry.shader, uniforms: entry.uniforms || null }; if (entry.scale != null) { pass.scale = entry.scale; } passes.push(pass); } } return passes; } normalizePostShaders () { return this.normalizePostShaderList(this.postShaders); } getPostPassesForLayer (layer) { const fromLayer = this.normalizePostShaderList(layer.postShaders); if (fromLayer.length) { return fromLayer; } // Back-compat: scene.postShaders apply to the default layer only. if (layer.name === RenderLayer.DEFAULT_NAME) { return this.normalizePostShaders(); } return []; } draw () { if (this.destroyed || !this.glContext) { return; } this.g_fixSize(); const gl = this.glContext; const layers = this.renderLayers && this.renderLayers.length ? this.renderLayers : [new RenderLayer(RenderLayer.DEFAULT_NAME)]; // Canvas clear (background behind all layers). gl.endOffscreenPass(); if (this.renderBackground) { gl.clear( this.backgroundColor.r, this.backgroundColor.g, this.backgroundColor.b, 1 ); } else { gl.clearTransparent(); } this.#ensureDrawOrder(); const sortedActiveObjects = this._sortedActiveObjects; // Reuse per-layer buckets so we do not allocate new arrays every frame. const byLayer = this._byLayer || (this._byLayer = Object.create(null)); const byLayerNames = this._byLayerNames || (this._byLayerNames = []); for (let i = 0; i < byLayerNames.length; i++) { byLayer[byLayerNames[i]].length = 0; } byLayerNames.length = 0; for (let i = 0; i < sortedActiveObjects.length; i++) { const obj = sortedActiveObjects[i]; if (obj.destroyed || !obj.renderer || !obj.renderer.visible) { continue; } const name = obj.renderer.layerName; let bucket = byLayer[name]; if (!bucket) { bucket = []; byLayer[name] = bucket; } if (bucket.length === 0) { byLayerNames.push(name); } bucket.push(obj); } const builtins = { u_resolution: [gl._lastWidth, gl._lastHeight], u_time: this.postTime }; for (let li = 0; li < layers.length; li++) { const renderLayer = layers[li]; const layerObjects = byLayer[renderLayer.name]; if (!layerObjects || !layerObjects.length) { continue; } gl.beginOffscreenPass(); gl.clearTransparent(); for (let i = 0; i < layerObjects.length; i++) { layerObjects[i].draw(this.context); } const postPasses = this.getPostPassesForLayer(renderLayer); let texture = gl.colorTextures[0]; if (postPasses.length) { texture = gl.applyPostShaders(postPasses, builtins, { toCanvas: false }); } else { gl.endOffscreenPass(); } gl.blitToCanvas(texture, renderLayer.composite || "alpha"); } } }