UNPKG

playcanvas

Version:

Open-source WebGL/WebGPU 3D engine for the web

602 lines (601 loc) 21.5 kB
var __defProp = Object.defineProperty; var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); import { TRACEID_RENDER_ACTION } from "../../core/constants.js"; import { Debug } from "../../core/debug.js"; import { Tracing } from "../../core/tracing.js"; import { EventHandler } from "../../core/event-handler.js"; import { sortPriority } from "../../core/sort.js"; import { LAYERID_DEPTH } from "../constants.js"; import { RenderAction } from "./render-action.js"; class LayerComposition extends EventHandler { /** * Create a new layer composition. * * @param {string} [name] - Optional non-unique name of the layer composition. Defaults to * "Untitled" if not specified. */ constructor(name = "Untitled") { super(); // Composition can hold only 2 sublayers of each layer /** * A read-only array of {@link Layer} sorted in the order they will be rendered. * * @type {Layer[]} */ __publicField(this, "layerList", []); /** * A mapping of {@link Layer#id} to {@link Layer}. * * @type {Map<number, Layer>} * @ignore */ __publicField(this, "layerIdMap", /* @__PURE__ */ new Map()); /** * A mapping of {@link Layer#name} to {@link Layer}. * * @type {Map<string, Layer>} * @ignore */ __publicField(this, "layerNameMap", /* @__PURE__ */ new Map()); /** * A mapping of {@link Layer} to its opaque index in {@link layerList}. * * @type {Map<Layer, number>} * @ignore */ __publicField(this, "layerOpaqueIndexMap", /* @__PURE__ */ new Map()); /** * A mapping of {@link Layer} to its transparent index in {@link layerList}. * * @type {Map<Layer, number>} * @ignore */ __publicField(this, "layerTransparentIndexMap", /* @__PURE__ */ new Map()); /** * A read-only array of boolean values, matching {@link layerList}. True means only * semi-transparent objects are rendered, and false means opaque. * * @type {boolean[]} * @ignore */ __publicField(this, "subLayerList", []); /** * A read-only array of boolean values, matching {@link layerList}. True means the * layer is rendered, false means it's skipped. * * @type {boolean[]} */ __publicField(this, "subLayerEnabled", []); // more granular control on top of layer.enabled (ANDed) /** * An array of {@link CameraComponent}s. * * @type {CameraComponent[]} * @ignore */ __publicField(this, "cameras", []); /** * A set of {@link Camera}s. * * @type {Set<Camera>} * @ignore */ __publicField(this, "camerasSet", /* @__PURE__ */ new Set()); /** * The actual rendering sequence, generated based on layers and cameras * * @type {RenderAction[]} * @ignore */ __publicField(this, "_renderActions", []); /** * True if the composition needs to be updated before rendering. * * @ignore */ __publicField(this, "_dirty", false); this.name = name; this._opaqueOrder = {}; this._transparentOrder = {}; } destroy() { this.destroyRenderActions(); } destroyRenderActions() { this._renderActions.forEach((ra) => ra.destroy()); this._renderActions.length = 0; } markDirty() { this._dirty = true; } _update() { const len = this.layerList.length; if (!this._dirty) { for (let i = 0; i < len; i++) { if (this.layerList[i]._dirtyComposition) { this._dirty = true; break; } } } if (this._dirty) { this._dirty = false; this.cameras.length = 0; this.camerasSet.clear(); for (let i = 0; i < len; i++) { const layer = this.layerList[i]; layer._dirtyComposition = false; for (let j = 0; j < layer.cameras.length; j++) { const cameraComponent = layer.cameras[j]; if (!this.camerasSet.has(cameraComponent.camera)) { this.camerasSet.add(cameraComponent.camera); this.cameras.push(cameraComponent); } } } if (this.cameras.length > 1) { sortPriority(this.cameras); } const cameraLayers = []; let renderActionCount = 0; this.destroyRenderActions(); for (let i = 0; i < this.cameras.length; i++) { const camera = this.cameras[i]; cameraLayers.length = 0; if (camera.camera.framePasses.length > 0) { this.addDummyRenderAction(renderActionCount, camera); renderActionCount++; continue; } let cameraFirstRenderAction = true; const cameraFirstRenderActionIndex = renderActionCount; let lastRenderAction = null; let postProcessMarked = false; for (let j = 0; j < len; j++) { const layer = this.layerList[j]; const isLayerEnabled = layer.enabled && this.subLayerEnabled[j]; if (isLayerEnabled) { if (layer.cameras.length > 0) { if (camera.layers.indexOf(layer.id) >= 0) { cameraLayers.push(layer); if (!postProcessMarked && layer.id === camera.disablePostEffectsLayer) { postProcessMarked = true; if (lastRenderAction) { lastRenderAction.triggerPostprocess = true; } } const isTransparent = this.subLayerList[j]; lastRenderAction = this.addRenderAction( renderActionCount, layer, isTransparent, camera, cameraFirstRenderAction, postProcessMarked ); renderActionCount++; cameraFirstRenderAction = false; } } } } if (cameraFirstRenderActionIndex < renderActionCount) { lastRenderAction.lastCameraUse = true; } if (!postProcessMarked && lastRenderAction) { lastRenderAction.triggerPostprocess = true; } if (camera.renderTarget && camera.postEffectsEnabled) { this.propagateRenderTarget(cameraFirstRenderActionIndex - 1, camera); } } this._logRenderActions(); } } getNextRenderAction(renderActionIndex) { Debug.assert(this._renderActions.length === renderActionIndex); const renderAction = new RenderAction(); this._renderActions.push(renderAction); return renderAction; } addDummyRenderAction(renderActionIndex, camera) { const renderAction = this.getNextRenderAction(renderActionIndex); renderAction.camera = camera; renderAction.useCameraPasses = true; } // function adds new render action to a list, while trying to limit allocation and reuse already allocated objects addRenderAction(renderActionIndex, layer, isTransparent, camera, cameraFirstRenderAction, postProcessMarked) { let rt = layer.id !== LAYERID_DEPTH ? camera.renderTarget : null; let used = false; const renderActions = this._renderActions; for (let i = renderActionIndex - 1; i >= 0; i--) { if (renderActions[i].camera === camera && renderActions[i].renderTarget === rt) { used = true; break; } } if (postProcessMarked && camera.postEffectsEnabled) { rt = null; } const renderAction = this.getNextRenderAction(renderActionIndex); renderAction.triggerPostprocess = false; renderAction.layer = layer; renderAction.transparent = isTransparent; renderAction.camera = camera; renderAction.renderTarget = rt; renderAction.firstCameraUse = cameraFirstRenderAction; renderAction.lastCameraUse = false; const needsCameraClear = cameraFirstRenderAction || !used; const needsLayerClear = layer.clearColorBuffer || layer.clearDepthBuffer || layer.clearStencilBuffer; if (needsCameraClear || needsLayerClear) { renderAction.setupClears(needsCameraClear ? camera : void 0, layer); } return renderAction; } // executes when post-processing camera's render actions were created to propagate rendering to // render targets to previous camera as needed propagateRenderTarget(startIndex, fromCamera) { for (let a = startIndex; a >= 0; a--) { const ra = this._renderActions[a]; const layer = ra.layer; if (ra.renderTarget && layer.id !== LAYERID_DEPTH) { break; } if (layer.id === LAYERID_DEPTH) { continue; } if (ra.useCameraPasses) { break; } const thisCamera = ra?.camera.camera; if (thisCamera) { if (!fromCamera.camera.rect.equals(thisCamera.rect) || !fromCamera.camera.scissorRect.equals(thisCamera.scissorRect)) { break; } } ra.renderTarget = fromCamera.renderTarget; } } // logs render action and their properties _logRenderActions() { if (Tracing.get(TRACEID_RENDER_ACTION)) { Debug.trace(TRACEID_RENDER_ACTION, `Render Actions for composition: ${this.name}`); for (let i = 0; i < this._renderActions.length; i++) { const ra = this._renderActions[i]; const camera = ra.camera; if (ra.useCameraPasses) { Debug.trace(TRACEID_RENDER_ACTION, `${i}CustomPasses Cam: ${camera ? camera.entity.name : "-"}`); } else { const layer = ra.layer; const enabled = layer.enabled && this.isEnabled(layer, ra.transparent); const clear = (ra.clearColor ? "Color " : "..... ") + (ra.clearDepth ? "Depth " : "..... ") + (ra.clearStencil ? "Stencil" : "......."); Debug.trace( TRACEID_RENDER_ACTION, `${i + ` Cam: ${camera ? camera.entity.name : "-"}`.padEnd(22, " ") + ` Lay: ${layer.name}`.padEnd(22, " ") + (ra.transparent ? " TRANSP" : " OPAQUE") + (enabled ? " ENABLED " : " DISABLED") + ` RT: ${ra.renderTarget ? ra.renderTarget.name : "-"}`.padEnd(30, " ")} Clear: ${clear}${ra.firstCameraUse ? " CAM-FIRST" : ""}${ra.lastCameraUse ? " CAM-LAST" : ""}${ra.triggerPostprocess ? " POSTPROCESS" : ""}` ); } } } } _isLayerAdded(layer) { const found = this.layerIdMap.get(layer.id) === layer; Debug.assert(!found, `Layer is already added: ${layer.name}`); return found; } _isSublayerAdded(layer, transparent) { const map = transparent ? this.layerTransparentIndexMap : this.layerOpaqueIndexMap; if (map.get(layer) !== void 0) { Debug.error(`Sublayer ${layer.name}, transparent: ${transparent} is already added.`); return true; } return false; } // Whole layer API /** * Adds a layer (both opaque and semi-transparent parts) to the end of the {@link layerList}. * * @param {Layer} layer - A {@link Layer} to add. */ push(layer) { if (this._isLayerAdded(layer)) return; this.layerList.push(layer); this.layerList.push(layer); this._opaqueOrder[layer.id] = this.subLayerList.push(false) - 1; this._transparentOrder[layer.id] = this.subLayerList.push(true) - 1; this.subLayerEnabled.push(true); this.subLayerEnabled.push(true); this._updateLayerMaps(); this._dirty = true; this.fire("add", layer); } /** * Inserts a layer (both opaque and semi-transparent parts) at the chosen index in the * {@link layerList}. * * @param {Layer} layer - A {@link Layer} to add. * @param {number} index - Insertion position. */ insert(layer, index) { if (this._isLayerAdded(layer)) return; this.layerList.splice(index, 0, layer, layer); this.subLayerList.splice(index, 0, false, true); const count = this.layerList.length; this._updateOpaqueOrder(index, count - 1); this._updateTransparentOrder(index, count - 1); this.subLayerEnabled.splice(index, 0, true, true); this._updateLayerMaps(); this._dirty = true; this.fire("add", layer); } /** * Removes a layer (both opaque and semi-transparent parts) from {@link layerList}. * * @param {Layer} layer - A {@link Layer} to remove. */ remove(layer) { let id = this.layerList.indexOf(layer); delete this._opaqueOrder[id]; delete this._transparentOrder[id]; while (id >= 0) { this.layerList.splice(id, 1); this.subLayerList.splice(id, 1); this.subLayerEnabled.splice(id, 1); id = this.layerList.indexOf(layer); this._dirty = true; this.fire("remove", layer); } const count = this.layerList.length; this._updateOpaqueOrder(0, count - 1); this._updateTransparentOrder(0, count - 1); this._updateLayerMaps(); } // Sublayer API /** * Adds part of the layer with opaque (non semi-transparent) objects to the end of the * {@link layerList}. * * @param {Layer} layer - A {@link Layer} to add. */ pushOpaque(layer) { if (this._isSublayerAdded(layer, false)) return; this.layerList.push(layer); this._opaqueOrder[layer.id] = this.subLayerList.push(false) - 1; this.subLayerEnabled.push(true); this._updateLayerMaps(); this._dirty = true; this.fire("add", layer); } /** * Inserts an opaque part of the layer (non semi-transparent mesh instances) at the chosen * index in the {@link layerList}. * * @param {Layer} layer - A {@link Layer} to add. * @param {number} index - Insertion position. */ insertOpaque(layer, index) { if (this._isSublayerAdded(layer, false)) return; this.layerList.splice(index, 0, layer); this.subLayerList.splice(index, 0, false); const count = this.subLayerList.length; this._updateOpaqueOrder(index, count - 1); this.subLayerEnabled.splice(index, 0, true); this._updateLayerMaps(); this._dirty = true; this.fire("add", layer); } /** * Removes an opaque part of the layer (non semi-transparent mesh instances) from * {@link layerList}. * * @param {Layer} layer - A {@link Layer} to remove. */ removeOpaque(layer) { for (let i = 0, len = this.layerList.length; i < len; i++) { if (this.layerList[i] === layer && !this.subLayerList[i]) { this.layerList.splice(i, 1); this.subLayerList.splice(i, 1); len--; this._updateOpaqueOrder(i, len - 1); this.subLayerEnabled.splice(i, 1); this._dirty = true; if (this.layerList.indexOf(layer) < 0) { this.fire("remove", layer); } break; } } this._updateLayerMaps(); } /** * Adds part of the layer with semi-transparent objects to the end of the {@link layerList}. * * @param {Layer} layer - A {@link Layer} to add. */ pushTransparent(layer) { if (this._isSublayerAdded(layer, true)) return; this.layerList.push(layer); this._transparentOrder[layer.id] = this.subLayerList.push(true) - 1; this.subLayerEnabled.push(true); this._updateLayerMaps(); this._dirty = true; this.fire("add", layer); } /** * Inserts a semi-transparent part of the layer at the chosen index in the {@link layerList}. * * @param {Layer} layer - A {@link Layer} to add. * @param {number} index - Insertion position. */ insertTransparent(layer, index) { if (this._isSublayerAdded(layer, true)) return; this.layerList.splice(index, 0, layer); this.subLayerList.splice(index, 0, true); const count = this.subLayerList.length; this._updateTransparentOrder(index, count - 1); this.subLayerEnabled.splice(index, 0, true); this._updateLayerMaps(); this._dirty = true; this.fire("add", layer); } /** * Removes a transparent part of the layer from {@link layerList}. * * @param {Layer} layer - A {@link Layer} to remove. */ removeTransparent(layer) { for (let i = 0, len = this.layerList.length; i < len; i++) { if (this.layerList[i] === layer && this.subLayerList[i]) { this.layerList.splice(i, 1); this.subLayerList.splice(i, 1); len--; this._updateTransparentOrder(i, len - 1); this.subLayerEnabled.splice(i, 1); this._dirty = true; if (this.layerList.indexOf(layer) < 0) { this.fire("remove", layer); } break; } } this._updateLayerMaps(); } /** * Gets index of the opaque part of the supplied layer in the {@link layerList}. * * @param {Layer} layer - A {@link Layer} to find index of. * @returns {number} The index of the opaque part of the specified layer, or -1 if it is not * part of the composition. */ getOpaqueIndex(layer) { return this.layerOpaqueIndexMap.get(layer) ?? -1; } /** * Gets index of the semi-transparent part of the supplied layer in the {@link layerList}. * * @param {Layer} layer - A {@link Layer} to find index of. * @returns {number} The index of the semi-transparent part of the specified layer, or -1 if it * is not part of the composition. */ getTransparentIndex(layer) { return this.layerTransparentIndexMap.get(layer) ?? -1; } isEnabled(layer, transparent) { if (layer.enabled) { const index = transparent ? this.getTransparentIndex(layer) : this.getOpaqueIndex(layer); if (index >= 0) { return this.subLayerEnabled[index]; } } return false; } /** * Update maps of layer IDs and names to match the layer list. * * @private */ _updateLayerMaps() { this.layerIdMap.clear(); this.layerNameMap.clear(); this.layerOpaqueIndexMap.clear(); this.layerTransparentIndexMap.clear(); for (let i = 0; i < this.layerList.length; i++) { const layer = this.layerList[i]; this.layerIdMap.set(layer.id, layer); this.layerNameMap.set(layer.name, layer); const subLayerIndexMap = this.subLayerList[i] ? this.layerTransparentIndexMap : this.layerOpaqueIndexMap; subLayerIndexMap.set(layer, i); } } /** * Finds a layer inside this composition by its ID. Null is returned, if nothing is found. * * @param {number} id - An ID of the layer to find. * @returns {Layer|null} The layer corresponding to the specified ID. Returns null if layer is * not found. */ getLayerById(id) { return this.layerIdMap.get(id) ?? null; } /** * Finds a layer inside this composition by its name. Null is returned, if nothing is found. * * @param {string} name - The name of the layer to find. * @returns {Layer|null} The layer corresponding to the specified name. Returns null if layer * is not found. */ getLayerByName(name) { return this.layerNameMap.get(name) ?? null; } _updateOpaqueOrder(startIndex, endIndex) { for (let i = startIndex; i <= endIndex; i++) { if (this.subLayerList[i] === false) { this._opaqueOrder[this.layerList[i].id] = i; } } } _updateTransparentOrder(startIndex, endIndex) { for (let i = startIndex; i <= endIndex; i++) { if (this.subLayerList[i] === true) { this._transparentOrder[this.layerList[i].id] = i; } } } // Used to determine which array of layers has any sublayer that is // on top of all the sublayers in the other array. The order is a dictionary // of <layerId, index>. _sortLayersDescending(layersA, layersB, order) { let topLayerA = -1; let topLayerB = -1; for (let i = 0, len = layersA.length; i < len; i++) { const id = layersA[i]; if (order.hasOwnProperty(id)) { topLayerA = Math.max(topLayerA, order[id]); } } for (let i = 0, len = layersB.length; i < len; i++) { const id = layersB[i]; if (order.hasOwnProperty(id)) { topLayerB = Math.max(topLayerB, order[id]); } } if (topLayerA === -1 && topLayerB !== -1) { return 1; } else if (topLayerB === -1 && topLayerA !== -1) { return -1; } return topLayerB - topLayerA; } /** * Used to determine which array of layers has any transparent sublayer that is on top of all * the transparent sublayers in the other array. * * @param {number[]} layersA - IDs of layers. * @param {number[]} layersB - IDs of layers. * @returns {number} Returns a negative number if any of the transparent sublayers in layersA * is on top of all the transparent sublayers in layersB, or a positive number if any of the * transparent sublayers in layersB is on top of all the transparent sublayers in layersA, or 0 * otherwise. * @private */ sortTransparentLayers(layersA, layersB) { return this._sortLayersDescending(layersA, layersB, this._transparentOrder); } /** * Used to determine which array of layers has any opaque sublayer that is on top of all the * opaque sublayers in the other array. * * @param {number[]} layersA - IDs of layers. * @param {number[]} layersB - IDs of layers. * @returns {number} Returns a negative number if any of the opaque sublayers in layersA is on * top of all the opaque sublayers in layersB, or a positive number if any of the opaque * sublayers in layersB is on top of all the opaque sublayers in layersA, or 0 otherwise. * @private */ sortOpaqueLayers(layersA, layersB) { return this._sortLayersDescending(layersA, layersB, this._opaqueOrder); } } export { LayerComposition };